I have the following in the model:
我在模型中有以下内容:
before_save :set_defaults
def set_defaults
self.num_results ||= 5
end
And I create the object in my controller like this:
我在我的控制器中创建对象,如下所示:
Search.create!( :keyword => params[:keyword],
:ip_address => request.remote_ip,
:referring_page => request.referer )
Even though I haven't set a value for num_results
it's still getting saved as 0
(which is the default value in the DB schema). The callback function doesn't get called at all. Any clues?
即使我没有为num_results设置一个值,它仍然保存为0(这是数据库模式中的默认值)。根本没有调用回调函数。有什么线索吗?
Update:
更新:
I turns out the callback does get called, the problem is in:
我发现回调确实被调用,问题在于:
self.num_results ||= 5
self.num_results || = 5
How would I set the default value in ruby? As this doesn't seem to work.
我如何在ruby中设置默认值?因为这似乎不起作用。
1 个解决方案
#1
1
num_results is only set to 5, if num_result is nil. In your case it is set to 0 by default, so the assignemt does not do anything. Try to change your assignment to:
如果num_result为nil,则num_results仅设置为5。在您的情况下,默认设置为0,因此assignemt不执行任何操作。尝试将您的作业更改为:
self.num_results = 5
#1
1
num_results is only set to 5, if num_result is nil. In your case it is set to 0 by default, so the assignemt does not do anything. Try to change your assignment to:
如果num_result为nil,则num_results仅设置为5。在您的情况下,默认设置为0,因此assignemt不执行任何操作。尝试将您的作业更改为:
self.num_results = 5