Ruby on Rails:借助 << 修改模型属性的虚拟方法无法保存该属性
有带有属性注释(文本类型)的模型批准
def Ratification < ActiveRecord::Base
attr_accessor :add_comment
def add_comment=(text)
self.comment ||= ""
self.comment << "\r\n" + text
end
end
,如果我使用add_comment=,那么在保存对象之前就可以了。保存后评论更改被删除。
>> r = Ratification.last
Ratification Load (0.6ms) SELECT * FROM `ratifications` ORDER BY ratifications.id DESC LIMIT 1
=> #<Ratification id: 8, user_id: 686, comment: "dasads", created_at: "2010-06-25 13:16:24", updated_at: "2010-06-25 13:38:36">
>> r.comment
=> "dasads"
>> r.add_comment="text"
=> "text"
>> r.comment
=> "dasads\r\ntext"
>> r.save
SQL (0.7ms) BEGIN
SQL (0.2ms) COMMIT
=> true
>> r.reload
Ratification Load (1.6ms) SELECT * FROM `ratifications` WHERE (`ratifications`.`id` = 8)
=> #<Ratification id: 8, user_id: 686, comment: "dasads", created_at: "2010-06-25 13:16:24", updated_at: "2010-06-25 13:38:36">
>> r.comment
=> "dasads"
为什么?!
轨道2.3.8 红宝石1.8
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Hrrrm...这很奇怪,当我尝试执行以下操作时,我在 Rails 应用程序中看到类似的行为:
然后重新加载...原始名称正在重置!
但是,如果我执行 @s.name += "test"
那么即使在重新加载后,新名称也会被保存。
我不知道为什么<<就是这样的,但我通常在所有情况下都默认为 += ,所以我以前从未注意到它。更改为 += 对您有帮助吗?
编辑:看看API,也许是因为<<修改原始字符串,而 + 或 += 生成一个包含旧字符串的新字符串?也许rails以某种方式只保存它标记为新的东西(而不是修改过的?)
Hrrrm...that IS weird, I'm seeing similar behavior from my rails app when I try to do:
and then reload...the original name is getting reset!
HOWEVER, if I do @s.name += "test"
then even after reloading, the new name is saved.
I'm not sure why << is behaving like that, but I usually default to += in all cases, so I've never noticed it before. Does changing to += help you?
Edit: Looking at the API, maybe it's because << modifies the original string, whereas + or += makes a NEW string, that contains the old one? Maybe rails somehow only saves things that it has marked as new (rather than modified?)