railsy
railsy

Reputation: 495

undefined local variable or method `customer_id' but customer_id field exists and one to many association exists

I'm getting this error when trying to update the customer_id column in my users table but can't figure out why. User model has_many :orders and Order model belongs_to :user, orders table has the correct foreign key of users_id and other things that rely on this relationship are working fine.

error:

undefined local variable or method `customer_id' for #<Order:0x007ff27014f9f0>

app/models/order.rb:16:in `save_with_payment'
app/controllers/orders_controller.rb:53:in `block in create'
app/controllers/orders_controller.rb:52:in `create' 

order.rb

belongs_to :user

def save_with_payment
if valid?
  customer = Stripe::Customer.create(description: email, card: stripe_card_token)
  self.stripe_customer_token = customer.id
  self.user.update_column(customer_id, customer.id) # this is line 16
  save!

  Stripe::Charge.create(
      :amount => (total * 100).to_i, # in cents
      :currency => "usd",
      :customer => customer.id
  )

end
rescue Stripe::InvalidRequestError => e
logger.error "Stripe error while creating customer: #{e.message}"
errors.add :base, "There was a problem with your credit card."
false
end

orders_controller.rb

def create
if current_user
  @order = current_user.orders.new(params[:order])
else
  @order = Order.new(params[:order])
end
respond_to do |format|        # this is line 52
  if @order.save_with_payment # this is line 53

    format.html { redirect_to auctions_path, :notice => 'Your payment has been successfully processed and your credit card has been linked to your account.' }
    format.json { render json: @order, status: :created, location: @order }
    format.js
  else
    format.html { render action: "new" }
    format.json { render json: @order.errors, status: :unprocessable_entity }
    format.js
  end
end
end

user.rb

has_many :orders

Upvotes: 1

Views: 708

Answers (1)

Valery Kvon
Valery Kvon

Reputation: 4496

self.user.update_column(:customer_id, customer.id)

Upvotes: 3

Related Questions