简体   繁体   English

Rails:strong_params和getter / setter方法

[英]Rails: strong_params and getter/setter methods

I'm using strong_params in Rails 4. When I try using a custom setter method like this: 我在Rails 4中使用strong_params。当我尝试使用这样的自定义setter方法时:

def foo=(foo)
  @foo = foo
end

Then Rails records the attribute as null within the database. 然后Rails将该属性记录为数据库中的null。 If I remove the custom setter, then everything works fine. 如果我删除自定义setter,那么一切正常。 In Rails 3, custom setters were written like this, but perhaps things have changed? 在Rails 3中,自定义setter是这样编写的,但也许事情已经改变了? If so, how do custom setters now work? 如果是这样,自定义设置器现在如何工作?

I don't think this code worked on Rails 3. Are you certain about this? 我认为这段代码不适用于Rails 3.你确定这个吗? Because if you do this, you override the setter method created by ActiveRecord (which is responsible for storing data to DB). 因为如果这样做,您将覆盖由ActiveRecord创建的setter方法(它负责将数据存储到DB)。 Does your custom version of method look exactly like shown? 您的自定义方法版本看起来是否完全如图所示? What's the point of it? 有什么意义呢?

Try calling super . 试着打电话给super

def foo=(foo)
  @foo = foo
  super
end

PS: I checked and it does not work in Rails 3 (works with super ). PS:我查了一下,并没有在Rails 3的(作品有工作super )。

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

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