2016-10-20 32 views
0

不节能想不通这是为什么不节省..保存在控制器

我已经缩短我的简码,留下了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

在'create_barbie.save'后面检查'create_barbie.errors' –

+0

我现在要!!我不知道如何去他们..我使用'huh.inspect',它只是给我真/假 – ToddT

回答

2

的问题是,确实是,你before_save挂钩。挂钩的事情是,如果它返回false,它可以取消保存操作。在你的情况下,它确实返回false。如果您不打算取消保存,请始终返回真值。

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 
+0

arghhhhHHHHHHH !!!!!!这是问题!非常感谢你! – ToddT

2

第一个小提示:在开发过程中使用save!时,如果您不确定它为什么会失败。这会产生一个带有验证错误的异常,而不是仅返回false

对于您的问题,使用permithttp://api.rubyonrails.org/classes/ActionController/Parameters.html

Barbie.new(params.require(:barbie).permit(:merchant_id, ...))

+0

,这是唯一的问题是,它仍然没有工作..现在真正的困惑。我已更新我的代码以显示我现在正在做什么 – ToddT

相关问题