Sql 如何在where子句中选择2个或多个模型
在SQL中,您可以让Sql 如何在where子句中选择2个或多个模型,sql,ruby-on-rails-3,where,Sql,Ruby On Rails 3,Where,在SQL中,您可以让从… 但是如果我使用where,生成的sql将只从它所作用的模型中进行选择 例如: user has_many :posts post belongs_to :user Post.includes(:users)。其中('created_at
从…
但是如果我使用where
,生成的sql将只从它所作用的模型中进行选择
例如:
user has_many :posts
post belongs_to :user
Post.includes(:users)。其中('created_at<?'1.day.ago
)将具有
SELECT "posts".* FROM "posts" WHERE (created_at > '2013-03-06 07:37:09.010916')
但是我如何选择帖子和用户,这样它也会返回帖子和用户呢?更新:正如Saurabh指出的,加载的关联应该是:user而不是:users Includes用于加载关联记录,这意味着
@posts = Post.includes(:user)
@posts.each do |post|
post.user
end
@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
只会对数据库进行两次查询,一次用于获取帖子,另一次用于获取与@posts
关联的所有用户。Rails为您管理关联。简单
如果要从其他表中获取某个列值,请尝试以下操作
@posts = Post.includes(:user)
@posts.each do |post|
post.user
end
@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
首先,您的关联是错误的。当您说:
Post属于:user
时,您不能执行Post.includes(:users)
正确的方法是-
Post.includes(:user)
用于所属的关联
第二个,您可以通过以下操作从不同的表中选择一个值:
Post.includes(:user).where(:user => {:name => params[:name]})
上面的查询将为您提供用户名为params[:name]
的所有帖子,其中:name
是用户表中的字段