Billy Logan
Billy Logan

Reputation: 2520

How to update corresponding record with has_one association?

I have a User model that has_one Bike and user accepts_nested_attributes_for a bike.

class User < ApplicationRecord
  has_one :bike

  accepts_nested_attributes_for :bike
end

and

class Bike < ApplicationRecord
  belongs_to :profile
end

On my controller I pass bike's parameters like this:

params.require(:purchase).permit(bike_attributes: [:id, :type, :brand])

after that I am updating the current_user with the new info

def update
  current_user.update(purchase_params)
end

My problem is that with every new change for a current user, a new bike record gets created. For example If I update the information about bike 10 times for the current user, then 10 bike records will be created and only the last one Bike.last will hold the right user_id.

How to prevent database from that and really update only one corresponding record?

Thank you.

Upvotes: 1

Views: 686

Answers (1)

Shannon
Shannon

Reputation: 3018

Check if the Bike is sending across the id attribute in the params. You should include a hidden id field for the bike if it's not currently there.

Upvotes: 2

Related Questions