I'd like to submit a product ID and a retailer ID to my controller, if that combo exisiting in the DB I want to update that record with the submitted params, if not, create a new record.
My controller is below and currently I can see that if the the combo does not exist the record is created but when the combo is found it does a select query and the record is not updated.
How can I get it to update and not just select?
Thanks
Controller:
def AddNewPrice
@newPrice = ProductPrice.find_or_create_by(product_id: params[:product_id], retailer_id: params[:retailer_id])
end
Update
Sorry..Just to mentioned, when I update I want to update the price attribute that comes in as a param
What you're trying to do is actually create a record if the combination of product_id
and retailer_id
does not exist. If it does exist then there's nothing to do..
If you want to update attributes if it exists or create it if it doesn't you can use find_or_initialize_by
along with update_attributes
def AddNewPrice
@newPrice = ProductPrice.find_or_initialize_by(product_id: params[:product_id], retailer_id: params[:retailer_id])
@newPrice.update_attributes(price: "updated value")
end
As, its clear from method name that it finds record matching given conditions, or create a new record with product_id, and retailer_id given, if record does't exists. You need to do some thing like this to update records
def add_new_price
new_price = ProductPrice.find_or_create_by(product_id: params[:product_id], retailer_id: params[:retailer_id])
new_price.update_attributes({attr: params[:attr]})
end
Like the method name suggests it finds the object if it exists and creates it if not.
If you want to update something you can do something like this:
def AddNewPrice
@newPrice = ProductPrice.find_or_create_by(product_id: params[:product_id], retailer_id: params[:retailer_id])
@newPrice.my_attribute = 'updated value'
@newPrice.save
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With