1

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

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 的更改值传入,但在 setter 中添加对 Rails.logger 的调用似乎表明它甚至没有被调用。

我在这里想念什么?

4

2 回答 2

0

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

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

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

于 2012-10-24T16:26:57.990 回答
0

找到它:虚拟属性的字段没有作为文章的一部分传回,因此它们没有显示在 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' %>

解决了这个问题。

于 2012-10-25T10:01:48.627 回答