【问题标题】:Override has_many << function覆盖 has_many << 函数
【发布时间】:2013-04-16 08:39:31
【问题描述】:

我在 Rails 2 应用程序中有一些类:Group 有一些 group_items。每个group_item 都有一个多态ìtemusercontact

class Group < AR::Base
  has_many :group_items
  has_many :users,    :through => :group_items
  has_many :contacts, :through => :group_items
end

class GroupItem < Ar::Base
  belongs_to :group
  belongs_to :item, :polymorphic => true
  belongs_to :users :conditions =>
      [ "#{GroupItem.table_name}.item_type = ? ", User.to_s ],
      :foreign_key => 'item_id'
  belongs_to :contacts :conditions =>
      [ "#{GroupItem.table_name}.item_type = ? ", Contact.to_s ],
      :foreign_key => 'item_id'
  validates_presence_of :group_id, :item_id, :item_type
end

一切都很完美。但我可以使用这个功能:

@my_group.users << @my_user
@my_group.contacts << @my_contact

关联似乎太复杂了,无法做到这一点:

ActiveRecord::RecordInvalid for GroupItem: item_type must be filled

有什么方法可以使用这个函数,比如覆盖Groupusers&lt;&lt;函数?

问候

【问题讨论】:

    标签: ruby-on-rails polymorphic-associations ruby-on-rails-2 model-associations


    【解决方案1】:

    我找到了一个很好的解决方案,使用关联扩展

    has_many :users, :through => :group_items do
      def <<(user)
        group_item = proxy_owner.group_items.create({ :item => user })
        return false if !group_item.valid?
        return proxy_target
      end
    end
    

    【讨论】:

    • 我觉得很尴尬:如果项目没有通过验证,你甚至无法访问它来查看错误
    • @apneadiving 只是为了和原来的&lt;&lt;有相同的行为,当项目无法插入时返回false
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-25
    • 2010-10-30
    • 2015-03-12
    • 2011-05-31
    • 1970-01-01
    • 2020-11-24
    相关资源
    最近更新 更多