【发布时间】:2014-04-09 23:18:36
【问题描述】:
我正在使用 Ruby on Rails 4,并以这种方式覆盖了一些默认访问器方法:
class Article < ActiveRecord::Base
def title
self.get_title
end
def content
self.get_content
end
end
self.get_title 和 self.get_content 方法返回一些计算值,如下所示(注意:has_one_association 是 :has_one ActiveRecord::Association)
def get_title
self.has_one_association.title.presence || read_attribute(:title)
end
def get_content
self.has_one_association.content.presence || read_attribute(:content)
end
当我从数据库中找到并读取 @article 实例时,所有实例都按预期工作:title 和 content 值分别使用 self.has_one_association.title 和 self.has_one_association.content 输出。
但是,我发现当属性分配给 @article 时,@article 对象没有按预期更新。也就是说,在我的控制器中,我有:
def update
# params # => {:article => {:title => "New title", :content => "New content"})}
...
# BEFORE UPDATING
# @article.title # => "Old title" # Note: "Old title" come from the 'get_title' method since the 'title' accessor implementation
# @article.content # => "Old content" # Note: "Old content" come from the 'get_content' method since the 'content' accessor implementation
if @article.update_attributes(article_params)
# AFTER UPDATING
# @article.title # => "Old title"
# @article.content # => "Old content"
...
end
end
def article_params
params.require(:article).permit(:title, :content)
end
即使 @article 有效,它也没有在数据库中更新(!),我认为是因为我覆盖访问器的方式和/或 Rails 的方式 assign_attributes。当然,如果我删除 getter 方法,那么一切都会按预期工作。
这是一个错误吗?我该如何解决这个问题?或者,我应该采用另一种方法来完成我想要完成的事情吗?
【问题讨论】:
标签: ruby-on-rails ruby methods overwrite accessor