Rails has_many associations are not saved when only attributes are changed

Viewed 82

I have two models, Profile and Skill, where a profile has_many skills.

I am using Rails as an API and passing an array of skill objects.

I'm doing @profile.skills = @skills in the controller, where @skills is my data from the frontend.

Whenever I delete or add a new skill, the above works as expected - also, @profile.skills.replace(@skills) works just the same.

The associated object gets deleted or created in the database as well. All as expected.

However, if I only change one or more attributes on an already existing skill, the changes are not saved to the database.

If I log @profile.skills after the above line of code, it seems like the changes expected are present.

But it does not get saved to the database and on the next request the changes are obviously not present.

What am I doing wrong?

1 Answers

Have you tried to pass like this:

class Profile < ApplicationRecord
  has_many :skills 

  accepts_nested_attributes_for :skills 
end

or

class Profile < ApplicationRecord
  has_many :skills, autosave: true
end

after that, edit the same attribute of the same record and save

@profile.skills.same.same_attr = new_val
@profile.save

accepts_nested_attributes_for - it also adds autosave to asociations, and a lot of other things, you can see more in the documentation and source code https://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

a little bit about how autosave works for associations https://api.rubyonrails.org/classes/ActiveRecord/AutosaveAssociation.html

Related