9

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

1
  • WHAT are you trying to update in case the record is found? Because I don't see any extra update commands. The found-row would already have the values that you're querying for.
    – SHS
    Commented May 7, 2015 at 17:05

3 Answers 3

8

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

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
1
  • This way the product price will be created then updated which will run two queries to update and three queries to create.
    – Leo Correa
    Commented May 7, 2015 at 17:53
4

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.