两个模型用户和文章的关系为:
用户 has_one 文章
文章 belongs_to 用户
-User有一个名为'status'的字段
-Article有一个名为'thing_i_need'的字段
class User < ActiveRecord::Base
has_one :article, foreign_key: request_id
# status :integer
end
class Article < ActiveRecord::Base
belongs_to :user, foreign_key: request_id
# thing_i_need :string
end
查询:User.where(status: 'xyz').last.article.thing_i_need
目前,会触发两个查询来获取'thing_i_need'
在一个查询中以任何方式执行此操作?
this有帮助吗?
答案 0 :(得分:1)
Article.includes('user').where('users.status = ? and articals.request_id = users.request_id', 'xyz').first.thing_i_need
答案 1 :(得分:1)
你可以试试这个
User.joins(:article).where(status: 'xyz').pluck('articles.thing_i_need').last
答案 2 :(得分:0)
您可以使用用户加入
Article.find(
:all,
:joins => :users,
:conditions => {
:users => {
:status => 'xyz'
}
}
).last.thing_i_need