无法弄清楚为什么不能保存..
我为了简洁而缩短了我的代码,省略了end
和其他不重要的事情。
我在控制器中遇到了这个问题:
create_barbie = Barbie.new(params.require(:barbie).permit(:merchant_id,
:auth_token,:marketplace))
huh = create_barbie.save! #this is returning ActiveRecord::RecordNotSaved
#(Failed to save the record)
在失败之前create_barbie
看起来像这样:
id: nil, merchant_id: "A340I3XXXX", auth_token: "13245", marketplace:
"abcded", created_at: nil, updated_at: nil, shopify_domain: nil, shop_id:
nil, three_speed: nil>
所以我的params
过得很好,并且已经填充,只是某些原因记录没有保存?
在我的Barbie
模型中,我有以下内容:
class Barbie < ActiveRecord::Base
belongs_to :shop
validates :merchant_id, presence: true
validates :auth_token, presence: true
before_save :assign_three_speed
NON_US_MARKETPLACES = ["1234", "abcd"]
在Barbie
模型中的私有方法中,我有:
private
def assign_three_speed
if NON_US_MARKETPLACES.include?(marketplace)
self.three_speed = false
else
self.three_speed = true
end
end
所有数据都是正确的,字段正在设置,它只是没有保存..不知道为什么??
答案 0 :(得分:2)
首先提示一点:当你不确定它为什么会失败时,在开发过程中使用save!
。这会引发验证错误的异常,而不仅仅是返回false
。
对于您的问题,请使用permit
:
http://api.rubyonrails.org/classes/ActionController/Parameters.html
Barbie.new(params.require(:barbie).permit(:merchant_id, ...))
答案 1 :(得分:2)
The issue is, indeed, with your before_save
hook. The thing with the hook is that it can cancel the save operation if it returns false
. And in your case it does return false
. If you don't intend to cancel save, return a truthy value always.
def assign_three_speed
if NON_US_MARKETPLACES.include?(marketplace)
self.three_speed = false
else
self.three_speed = true
end
true # don't cancel save
end