Reputation: 21618
I have an Article
model which is belongs_to
a user
so here I'm finding the user of a specific article as below:
article = Article.find(params[:id])
user = User.find(article.user_id)
As you see I achieve this via two queries, but I just want to have this in one single query. What you recommend? tnx.
Upvotes: 0
Views: 120
Reputation: 4023
How about a join
?
user = User.joins(:articles).where(articles: {id: params[:id]}).first
Upvotes: 1
Reputation: 8638
Sorry: as long as you want two objects, there is no way in Rails to select the data with one query.
You could construct a query that selects data of Article
and User
at the same time, store the user specific data in non DB attributes of Article
like
article = Article.where(id: params[:id]).joins(:user).select('articles.title, users.name').first
puts article.attributes['name']
that select all data in one query, but that really spoils Rails. You won't get an User
instance.
Upvotes: 1
Reputation: 7225
try this out:-
article = Article.includes(:user).where("articles.id = ?", params[:id]).first
now you can access user like article.user and no other query will get triggered.
this is known as eager loading:-
read more about it on rails guide.
http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations
see also:
http://railscasts.com/episodes/22-eager-loading
http://railscasts.com/episodes/22-eager-loading-revised
Upvotes: 0