在Rails中,关联对象的write_attribute等效于什么?

7

我想重写关联的setter方法,但是write_attribute()不起作用 - 可能是因为这个方法只适用于数据库列。

我已经尝试过super(),但它也不起作用(虽然我并不认为会有用……但还是值得一试的)。

我该如何重写setter方法?以下是我的尝试:

  def parent=(value)
    # this line needs to be changed
    write_attribute(:parent, value)

    if value.subject.start_with?('Re:')
      self.subject = "#{value.subject}"
    else
      self.subject = "Re: #{value.subject}"
    end

    self.receivers << value.sender
  end
4个回答

12

对我起作用的方法如下:

def parent=(new_parent)
  # do stuff before setting the new parent...

  association(:parent).writer(new_parent)
end

3
我找到了一种方法,但我对此感到不安:
  alias_method :old_parent=, :parent=

  def parent=(value)
    self.old_parent = value

    if value.subject.start_with?('Re:')
      self.subject = "#{value.subject}"
    else
      self.subject = "Re: #{value.subject}"
    end

    self.receivers << value.sender
  end

我不太喜欢Rails的一件事情是,每当你想做一些略有不同但并不过分的事情时,“如何”做就与你的直觉大不相同。如果你知道了这些例外规则,那么这并不是个问题,但是在学习阶段,这种不规则性和不一致性会让学习变得更加困难,而不是更容易。
Java可能一开始更难学,但它更加一致。一旦你用Java思考,你的直觉可以帮助你更进一步。而在Rails中,这并不适用。Rails是关于记忆要调用的方法和如何做事情的,而在Java中,你可以更多地进行推理...而智能感知会填补剩下的部分。
我只是有点失望。对我来说,这是一个反复出现的模式——我想做一些比框架示例“稍微复杂一些”的事情...但“如何”做却不一致,并且需要花费30分钟甚至数小时才能找到答案。

2

在 Rails 4.2.1 文档中:

# Association methods are generated in a module that is included into the model class,
# which allows you to easily override with your own methods and call the original
# generated method with +super+. For example:
#
#   class Car < ActiveRecord::Base
#     belongs_to :owner
#     belongs_to :old_owner
#     def owner=(new_owner)
#       self.old_owner = self.owner
#       super
#     end
#   end

0

而不是

def parent=(value)
  write_attribute(:parent, value)
end  

你不能简单地这样做吗:

def parent=(parent)
  parent_id = parent.id
end  

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接