ActiveRecord includes. Specify included columns

后端 未结 6 462
野的像风
野的像风 2020-12-02 17:08

I have model Profile. Profile has_one User. User model has field email. When I call

Profile.some_scope.includes(:user)

it calls

<         


        
6条回答
  •  情话喂你
    2020-12-02 17:55

    You need extra belongs to in the model.

    For simple association:

    belongs_to :user_restricted, -> { select(:id, :email) }, class_name: 'User'
    

    For Polymorphic association (for example, :commentable):

    belongs_to :commentable_restricted, -> { select(:id, :title) }, polymorphic: true, foreign_type: :commentable_type, foreign_key: :commentable_id
    

    You can choose whatever belongs_to name you want. For the examples given above, you can use them like Article.featured.includes(:user_restricted), Comment.recent.includes(:commentable_restricted) etc.

提交回复
热议问题