Rails Joins and include columns from joins table

后端 未结 5 1217
小鲜肉
小鲜肉 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条回答
  •  长情又很酷
    2020-12-13 05:07

    I don't think that you can load users and profiles with join in Rails. I think that in earlier versions of Rails ( < 2.1) loading of associated models was done with joins, but it was not efficient. Here you have some explanation and links to other materials.

    So even if you explicite say that you want to join it, Rails won't map it to associated models. So if you say Profile.whatever_here it will always be mapped to Profile object.

    If you still want to do what you said in question, then you can call custom sql query and process results by yourself:

    p = ActiveRecord::Base.connection.execute("SELECT * FROM profiles JOIN users ON profiles.user_id = users.id LIMIT 1")
    

    and get results row by row with:

    p.fetch_row
    

    It will already be mappet to an array.

    Your errors are because you are calling first_name and user method on AciveRecord::Relation object and it stores an array of Profile objects, not a single object. So

    p = Profile.joins(:user).limit(1)
    p[0].first_name
    

    shoud work.

    Better way to fetch only one record is to call:

    p = Profile.joins(:user).first
    p.first_name
    p.user
    

    But when you call p.user it will query database. To avoid it, you can use include, but if you load only one profile object, it is useless. It will make a difference if you load many profiles at a time and want to inlcude users table.

提交回复
热议问题