【问题标题】:rails polymorphic many-to-many associationrails 多态多对多关联
【发布时间】:2013-07-13 06:49:51
【问题描述】:

我有这些模型:

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

加上许多其他解决方案,但无法正常工作

谢谢!

【问题讨论】:

  • 我只能想象语言学家看到这个会经历的痛苦...... :)
  • 如果您没有公司关系,您希望它如何工作?

标签: ruby-on-rails activerecord polymorphic-associations


【解决方案1】:

您可以执行以下操作

Category.first.categorizables.where(categorizable_type: 'Company')

这将使用您的关系架构选择与 Category 关联的所有公司。

还阅读了一些关于 has_many :through 关联的信息,因为我认为你不太明白 http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-30
    • 2021-03-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多