繁体   English   中英

Rails 3虚拟属性未保存

[英]Rails 3 virtual attributes not saving

我有一个带有虚拟属性的模型:

attr_accessible :published_at

def published_at_text
  I18n.localize(published_at, format: :long_no_day_with_seconds) if published_at
end

def published_at_text=(text)
  self.published_at = Chronic.parse(text)
end

这在单元测试中工作正常,但是在视图中更改了Published_at_text字段时不会保存。 我试过使用attr_accessible :published_at_text ,并添加published_at_will_change! setter方法,但我无法使它工作。

development.log显示,已传递了已更改的published_at_text值,但是在设置器中添加对Rails.logger的调用似乎表明它甚至没有被调用。

我在这里想念什么?

好吧,您没有提供使用params哈希创建对象的控制器方法,但是我可以猜测。

您应该使用传递给控制器​​的参数来显式调用设置器。

然后检查该值是否在您的模型上更新。

找到了:虚拟属性的字段未作为文章的一部分传递回去,因此未在params哈希中显示。

替换为:

<%= text_field_tag 'article_published_at_text', @article.published_at_text, class: 'text_date show_seconds' %>

有了这个:

<%= text_field_tag 'article_published_at_text', @article.published_at_text, name: 'article[published_at_text]', class: 'text_date show_seconds' %>

解决了问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM