Ruby-on-rails 两个表上的 Rails where 子句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12706834/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 20:49:43  来源:igfitidea点击:

Rails where clause over two tables

ruby-on-railsrubywhere-clause

提问by Martin

I have the following model in rails application

我在 rails 应用程序中有以下模型

category => company => store

Store has a belongs_tocompany and company has a belongs_tocategory relationship. now i want to use a where method on a store object to retrieve all stores within the same category.

Store 有一个belongs_to公司,公司有一个belongs_to类别关系。现在我想在商店对象上使用 where 方法来检索同一类别中的所有商店。

I would like to have something like this

我想要这样的东西

@stores.nearbys(5).where("stores.company.category_id = xxx")

can somebody give me a tip on this

有人可以给我一个提示吗

回答by Erez Rabih

Try joins with where on the joined table:

尝试与连接表上的 where 连接:

@stores.nearbys(5).joins(:company).where("companies.category_id = xxx")

EDIT:

编辑:

To get the category of a store you will first have to delegate the category method to its company:

要获取商店的类别,您首先必须将类别方法委托给其公司:

class Store < ActiveRecord::Base
 belongs_to :company

 delegate :category, :to => :company
end

Now just call the method in your query:

现在只需在查询中调用该方法:

@stores.nearbys(5).joins(:company).where("companies.category_id = ?", self.company.id)

回答by Simone Carletti

wheresupports nested hash.

where支持嵌套哈希。

@stores.nearbys(5).where(:company => { :category_id => @category.id }, joins: company)

回答by Aayush Khandelwal

you can try this

你可以试试这个

 @category = Category.find xxx

 @store = @category.company.stores