【问题标题】:has_many through with :class_namehas_many 通过 :class_name
【发布时间】:2013-01-11 01:37:20
【问题描述】:

我有以下几点:

belongs_to :type, :class_name => :activity_type
belongs_to :activity_type # needed for has_one :through?
has_one :category, :through => :activity_type, :class_name => :activity_category

有没有办法使用“type”而不是“activity_type”来实现这种“has_one through”关系?

编辑:这行不通,多亏了神奇的“类型”一词,我没看到。

我现在拥有的是这样的:

  belongs_to :company
  belongs_to :type, :class_name => 'ActivityType', :foreign_key => 'activity_type_id'
  has_one :category, :through => :type, :class_name => 'ActivityCategory', :foreign_key => 'activity_category_id'

但它失败了

  no such column: activity_types.category_id

这是正确的,因为预期的列是“activity_types.activity_category_id”。我该如何解决?

【问题讨论】:

    标签: ruby-on-rails has-many-through relationships


    【解决方案1】:

    您以错误的方式使用关联。首先当你使用through: 然后class_nameforeign_key will be omitted。所以这就是它期待category_id 的原因。另外我认为你不应该通过重写默认选项来超载你的关联,因为当模型上有很多关联时,它开始看起来像一团糟并且难以理解。所以你可能应该把它写成belongs_to :activity_type,然后添加任何最适合你的名字,比如alias_method :type, :activity_type

    简而言之,这就是我向您提出的建议:

    belongs_to :company
    belongs_to :activity_type
    has_one :activity_category, :through => :activity_type
    
    alias_method :type, :activity_type
    alias_method :category, :activity_category
    

    【讨论】:

    • 谢谢,alias_method 正是我要找的。​​span>
    猜你喜欢
    • 2013-08-11
    • 2018-12-18
    • 1970-01-01
    • 2020-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多