简体   繁体   English

Rails 3虚拟属性未保存

[英]Rails 3 virtual attributes not saving

I have a model with virtual attributes: 我有一个带有虚拟属性的模型:

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

This works fine in the unit tests, but does not save when the published_at_text field is changed in the view. 这在单元测试中工作正常,但是在视图中更改了Published_at_text字段时不会保存。 I've tried using attr_accessible :published_at_text , and adding published_at_will_change! 我试过使用attr_accessible :published_at_text ,并添加published_at_will_change! to the setter method, but I can't get this to work. setter方法,但我无法使它工作。

The development.log shows that the changed value of published_at_text is being passed in, but adding a call to Rails.logger in the setter seems to indicate that it's not even getting called. development.log显示,已传递了已更改的published_at_text值,但是在设置器中添加对Rails.logger的调用似乎表明它甚至没有被调用。

What am I missing here? 我在这里想念什么?

Well, you do not provided your controller method that created your object using the params hash, but I can make a guess. 好吧,您没有提供使用params哈希创建对象的控制器方法,但是我可以猜测。

You should call explicity the setter with the parameter passed to the controller. 您应该使用传递给控制器​​的参数来显式调用设置器。

Then checks if the value gets updated on your model. 然后检查该值是否在您的模型上更新。

Found it: the fields for the virtual attribute weren't being passed back as part of the article, so they weren't being shown in the params hash. 找到了:虚拟属性的字段未作为文章的一部分传递回去,因此未在params哈希中显示。

Replacing this: 替换为:

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

with this: 有了这个:

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

fixed the problem. 解决了问题。

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

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