Praveen George
Praveen George

Reputation: 9715

How to Insert a value/update the existing value with a new value for a single column in Rails 4

I have a Customers Table in my Rails application, with columns to store the customer details. Once the customer login/signup the basic details of that customer will be saved into this table columns. In the Customer table there is a purchase_id column which is blank by default. When a customer purchase something from my site, a purchase_id will be created as @order.purchase_id. So once the purchase is done, I want to update the Customer Table with this @order.purchase_id like something the following:

@customer.purchase_id = @order.purchase_id

How to do this in my Customers controller ? I want to save/update the customer table to store the purchase_id permanently in my table.

Upvotes: 0

Views: 57

Answers (2)

Rajarshi Das
Rajarshi Das

Reputation: 12320

@Simone advice is perfect

use update also same like update_attributes

  Customer.update(@customer.id, :purchase_id => @order.purchase_id)

but better if you use the operation in model section it will be a good try

Or In model customer,

class Customer < ActiveRecord::Base
 has_one :order   
 after_save :purchase_update

 def purchase_update
    self.update_attribute(:purchase_id, order.purchase_id)
  end
end 

Upvotes: 1

Simone Carletti
Simone Carletti

Reputation: 176382

You are not saving the record.

@customer.purchase_id = @order.purchase_id
@customer.save!

or

@customer.update_attribute(:purchase_id, @order.purchase_id)

Upvotes: 1

Related Questions