如何从2对多关系中查找记录

时间:2013-11-11 10:30:25

标签: ruby-on-rails ruby

我想找到某个地区内某个类别的商家

我有以下型号

Business has many Categories through Categorizations
Category has many Businesses through Categorizations

Business has many Estates through Localizations
Estate has many Businesses through Localizations

在类别show action中我有

def show
  @category = Category.find(params[:id])
  @estate = Estate.find(current_user.estate_id)
  @businesses = @estate.businesses
end

显而易见的问题是,无论属于哪个类别,它都会归还所有业务。我试图添加一个.where(“category_id =?”,@ category_id)但我得到的列不存在错误

1 个答案:

答案 0 :(得分:1)

由于它似乎有效,这里的建议再次作为答案:)

@businesses = @estate.businesses.joins(:categories).where(categories: {id: @category.id})