Reputation: 2380
I'm not sure if I'm using properly the rails eager loading.
I'd like to call post.user.profile.first_name
in the view which will be simply post.user.name
thanks to delegation. I wanna do it with one query, so profile should be loaded along with user on the first query. I'm not sure if I'm doing it well.
Is this the way to go?
profile.rb
belongs_to :user
user.rb
has_one :profile
delegate :first_name, .... , to: :profile, allow_nil: true
has_many :posts
post.rb
belongs_to :user
has_one :user_profile, through: :user, source: :profile
posts_controller
Post.includes(:user, :user_profile).paginate.......
Upvotes: 0
Views: 27
Reputation: 3517
Try:
Post.joins(user: :profile).includes(user: :profile).paginate
The joins
is to ensure an inner join for an efficient and accurate query. The includes
is for the eager load, as you know.
Upvotes: 2