Reputation: 3258
Can't figure out why this isn't saving..
I've shortened my code for brevity, leaving out end
and other un-important things.
I have this getting hit in a controller:
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)
Before it fails create_barbie
looks like this:
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>
So my params
are coming over fine, and getting populated, just some reason the record isn't saving??
And in my Barbie
model I have the following:
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"]
In a private method within the Barbie
model I have this:
private
def assign_three_speed
if NON_US_MARKETPLACES.include?(marketplace)
self.three_speed = false
else
self.three_speed = true
end
end
All the data is correct, and the fields are getting set, its just not saving.. No idea why??
Upvotes: 1
Views: 1144
Reputation: 230521
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
Upvotes: 2
Reputation: 3139
First a little tip: Use save!
during development when you aren't sure why it does fail. This will raise an exception with the validation errors instead of just returning false
.
For your problems use permit
:
http://api.rubyonrails.org/classes/ActionController/Parameters.html
Barbie.new(params.require(:barbie).permit(:merchant_id, ...))
Upvotes: 2