Rails Joins and include columns from joins table

后端 未结 5 1186
小鲜肉
小鲜肉 2020-12-13 05:01

I don\'t understand how to get the columns I want from rails. I have two models - A User and a Profile. A User :has_many Profile (because users can revert back to an earlier

5条回答
  •  萌比男神i
    2020-12-13 05:33

    I have got round this problem by creating a VIEW in the database which is the join, and then referencing that as if it were a normal ActiveRecord table in the code. This is fine for getting data out of the database, but if you need to update it, then you'll need to go back to the base classes that represent the 'real' tables. I have found this method to be handy when doing reports that use biggish tables - you can get the data out all in one hit. I am surprised that this doesn't seem to be built into ActiveRecord, seems an obvious thing to me!

    So for you:

    IN SQL:

    CREATE VIEW User_Profiles
    AS
    SELECT P.*, U.first_name
    FROM Users U
    inner join Profiles P on U.id=P.user_id
    

    IN RUBY models file:

    class UserProfile < ActiveRecord::Base
      self.primary_key = :id 
      #same dependencies as profiles
    end
    

    **HINT... I always forget to set the owner of the view (I use postgres), so it blows up straight away with much cursing and self-recrimination.

提交回复
热议问题