2016-10-20 31 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

相關問題