Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find_or_create_by - not updating

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

like image 794
Geraint Avatar asked May 07 '15 16:05

Geraint


3 Answers

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
like image 129
Leo Correa Avatar answered Nov 08 '22 15:11

Leo Correa


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 image 41
Sarwan Kumar Avatar answered Nov 08 '22 17:11

Sarwan Kumar


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
like image 4
Mischa Avatar answered Nov 08 '22 17:11

Mischa