ruby-on-rails - Rails Habtm加入

标签 ruby-on-rails join has-and-belongs-to-many

我在类别,产品和品牌之间具有这种关系:

class Brand < ActiveRecord::Base
  has_many :products
end

class Category < ActiveRecord::Base
  has_and_belongs_to_many :products
end

class Product < ActiveRecord::Base
  has_and_belongs_to_many :categories
  belongs_to :brand
end

如何通过这种关系按指定品牌选择所有类别?
我尝试这样做,但出现错误
b = Brand.find(1)
Category.joins(:products).where(:products => b.products)

最佳答案

您对联接做了正确的事情,只是在其中定义中添加了更复杂的内容:

Category.joins(:products).where(:products => {:brand_id => 1})

关于ruby-on-rails - Rails Habtm加入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14243566/

相关文章:

jquery - 单击图像以在 Rails 中启动搜索

ruby-on-rails - 如何通过 cPanel 在共享主机上部署 Ruby on Rails 应用程序?

php - CakePHP:在 HABTM 中保存数据的正确格式是什么

ruby-on-rails - rails 3 : migration error when using json as a column type in an ActiveRecord backed by Postgres

ruby-on-rails - 选择关系不为空的记录

Mysql连接表结果为一行

rspec - Rails 5 before_destroy 抛出(:abort)

ruby-on-rails - Rails:是否可以为has_and_belongs_to_many关联添加额外的属性?

php - 自己加入 laravel

r - 合法连接上的 data.table 笛卡尔连接警告