2013-03-07 79 views
0

在SQL你可以有SELECT x,y FROM ...如何在選擇2個或多個模型回where子句

,但如果我用where,生成的SQL只能從它所在作用於車型選擇。

因此,例如:

user has_many :posts 
post belongs_to :user 

Post.includes(:users).where('created_at < ?' 1.day.ago)將有

SELECT "posts".* FROM "posts" WHERE (created_at > '2013-03-06 07:37:09.010916') 

,但我怎麼SELECT帖子和用戶,因此將返回崗位的用戶呢?

回答

1

更新:由於SAURABH指出,加載協會應該是:用戶,而不是:用戶

包括用於渴望負載關聯的記錄,也就是說,給出以下

@posts = Post.includes(:user) 
@posts.each do |post| 
    post.user 
end 

只有2查詢將被提交到數據庫,一個用於提取帖子,另一個用於提取所有與@posts相關聯的用戶。 Rails爲你管理關聯。簡單。

如果你想從不同的表中的某個列值,請嘗試以下

@posts = Post.joins(:user).select('posts.*, users.name AS user_name') 
@posts.first.user_name # will give you the name of the first user associated to the post 
+0

+1爲更新。休息一切都是正確的。 – 2013-03-07 09:27:09

0

首先,您的聯繫是錯誤的。當你說:post belongs_to :user時,你不能做Post.includes(:users)

正確的方法是 -

Post.includes(:user)belongs_to的關聯

,你可以這樣做選擇不同的表中的值:

Post.includes(:user).where(:user => {:name => params[:name]}) 

上面的查詢將會給你用戶名爲params[:name]其中:name是從用戶表中的字段的所有帖子。