覆盖集合<<方法

时间:2013-07-03 14:16:46

标签: ruby-on-rails ruby-on-rails-3

我有两个模型BoardFeed与加入的多对多关系:通过模型Subscription

最近我将root_id字段添加到Subscription,我想在@board.feeds << @feed时设置此字段,因此它会像@board.feeds << @feed, root_id: 10

根据rails docs,我可以覆盖这些方法,但不确定如何。

def feeds << (??? - how should I setup arguments here? )
  super
  #super creates new Subscription rekord, but how can I access it 
  #to set root_id field?

  #For now let say I accessed it as subscription

  if root_id 
    subscription.root_id = root_id
  else
    subscription.root_id = self.id
  end
  subscription.save
  #return something regular collection << returns
end

1 个答案:

答案 0 :(得分:0)

root_id上的Subscription是否代表BoardFeed的任何方面?你也许可以在Subscription的回调中完成这项工作:

# Subscription

before_save :assign_root_id

def assign_root_id
  self.root_id = feed.user.id # Whatever root is ....
end