我有这些模特:
class Company < ActiveRecord::Base
has_many :categorizings, as: :categorizable
has_many :categories, :through => :categorizings
class Categorizing < ActiveRecord::Base
belongs_to :category
belongs_to :categorizable, polymorphic: true
class Category < ActiveRecord::Base
has_many :categorizings
has_many :categorizables, through: :categorizings
如何让所有公司拥有特定类别?
我试过
Category.find_by_name("fff").companies
加上许多其他解决方案,但无法使其正常工作
THX!
答案 0 :(得分:1)
您可以执行以下操作
Category.first.categorizables.where(categorizable_type: 'Company')
将使用您的关系架构选择与Category相关联的所有公司。
还阅读了一些关于has_many :through
关联的内容,因为我认为你不太明白http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association