Ruby on rails Rails 3虚拟属性未保存

Ruby on rails Rails 3虚拟属性未保存,ruby-on-rails,ruby-on-rails-3,Ruby On Rails,Ruby On Rails 3,我有一个具有虚拟属性的模型: 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 这在单元测试中工作正常,但在视图中更改已

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

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
这在单元测试中工作正常,但在视图中更改已发布的_at_文本字段时不会保存。我试过使用
attr\u accessible:published\u at\u text
,添加
published\u at\u将会改变到setter方法,但我无法让它工作

development.log
显示正在传入已发布的_at_文本的更改值,但在setter中添加对Rails.logger的调用似乎表明它甚至没有被调用


我在这里遗漏了什么?

好吧,您没有提供使用params散列创建对象的控制器方法,但我可以猜一猜

您应该使用传递给控制器的参数调用setter


然后检查模型上的值是否得到更新。

找到了它:虚拟属性的字段没有作为文章的一部分传回,因此它们没有显示在参数散列中

替换此:

<%= 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' %>


修复了该问题。

i I18n逻辑应该在视图中的什么位置。因此,最好先调用setter。你如何更新属性?你可以提供你的单元测试代码,以便我们检查你是如何在那里完成任务的,以及为什么它不能在你的控件上工作。