Rails的 - 改变的关联不标记对象为脏 [英] Rails - Changing association doesn't mark object as dirty
问题描述
修改:添加澄清
由于以下两类
class Foo < ActiveRecord::Base
belongs_to :bar
end
class Bar < ActiveRecord::Base
end
当我更改栏上富,我想办法看到,foo的实例已更改:
When I change a bar on a foo, I would like a way to see that the foo instance has changed:
foo = Foo.find(x)
foo.bar # returns #<Bar id:1>
foo.bar = Bar.new
foo.changed? # returns false
foo.changes # returns an empty hash
我不想设定bar_id为肮脏的(因为它并没有改变),这将是不错的有以下几种:
I don't want to set bar_id as dirty (because it hasn't changed) It would be nice to have the following:
foo.changed? # returns true
foo.changes # returns {:bar => [#<Bar id: 1>, nil]}
有一个聪明的方法来破解这个到Rails?还有一个原因是,这不是Rails的一部分?
Is there a clever way to hack this into Rails? Is there a reason this is not part of Rails?
推荐答案
今天我面临同样的问题,并通过轨道源运行后,我发现了一个解决方法,应该做你脑子里想什么,如果我得到你的问题正确的做法。
I faced the same problem today and after running through the rails-source i found a workaround that should do what you had in mind, if i got your question the right way.
传送到您的例子中,code看起来应该是:
Transferred to your example the code should look like that:
class Foo < ActiveRecord::Base
belongs_to :bar
def info
bar.info
end
def info=(val)
@changed_attributes[:info] = self.info unless val == self.info
self.time_entry.update_attributes! :info => val
end
end
class Bar < ActiveRecord::Base
attr_accessible :info
end
这种方式,你丹通话.changed?和的.changes在富类的对象。
This way you dan call .changed? and .changes on objects of the Foo-class.
希望这有助于即使答案来得有点晚:)
hope this helps even if the answer comes a bit late :)
亲切的问候 基督教
BTW。遗憾的英文不好。我的工作是尽可能在我的红宝石技能;)的
这篇关于Rails的 - 改变的关联不标记对象为脏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!