[英]Rails: How do I call `self.save` in my model and have it persist in the database?
I'm trying to keep model logic within my model, but I can't get it to perform modifications on itself and have them persist in the database. 我正在尝试将模型逻辑保留在我的模型中,但是我无法让它对自身执行修改并让它们在数据库中保留。
In my controller: 在我的控制器中:
@article.perform_some_calulcations!
In my model: 在我的模型中:
def perform_some_calculations!
self.foo.gsub!(/regexp/, 'string')
self.save
end
If I drop debugger
statements into my method and after my call to it in the controller, @article.foo
has the correct value. 如果我将
debugger
语句放入我的方法中并在控制器中调用它之后, @article.foo
具有正确的值。 However, when I continue, it doesn't persist in the database and webrick doesn't report any UPDATE
statements. 但是,当我继续时,它不会在数据库中持久存在,并且webrick不会报告任何
UPDATE
语句。
What's going wrong? 出了什么问题? I don't know if I've ever had to do this before, but surely it's possible right?
我不知道我以前是否曾经这样做过,但肯定有可能吗?
Your problem was that if you modify an attribute "in place", this means: without assigning it a new value, then Rails will think that there is nothing new to be saved, so it "optimizes" the save away. 你的问题是如果你“修改”一个属性,这意味着:如果不给它赋一个新的值,那么Rails会认为没有什么新东西可以保存,所以它“优化”了豁免。
Each write accessor of your attribute will set a flag, so the save method will know that it should check whether the current value really differs from the value read from the database. 属性的每个写访问器都将设置一个标志,因此save方法将知道它应该检查当前值是否确实与从数据库中读取的值不同。 That's why
self.foo = self.foo.gsub(/regexp/, 'string')
works (note that the exclamation mark is not necessary here) . 这就是为什么
self.foo = self.foo.gsub(/regexp/, 'string')
有效(注意这里不需要感叹号) 。
If you need to modify an attribute "in place", for example with gsub!
如果您需要“就地”修改属性,例如使用
gsub!
or replace
, use: 或
replace
,使用:
def perform_some_calculations!
foo_will_change!
self.foo.gsub!(/regexp/, 'string')
self.save
end
Your attributes might be protected. 您的属性可能受到保护。 Check your log.
检查你的日志。 IF that is the case then
如果是这样的话
self.save!
or 要么
self.save(false)
try taking the exclamation point off your definition. 尝试从你的定义中删除感叹号。
self.foo = self.foo.gsub!(/regexp/, 'string')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.