Search code examples
ruby-on-railsruby-on-rails-4ruby-on-rails-5ruby-on-rails-6

Rails 5: update nested attributes through another model


I can not update nested attributes which is related with current model by 3rd model.

Focused model: Profile

class Profile < ApplicationRecord
  belongs_to :user
  has_many :phone_numbers

  ##Set nested attributes
  accepts_nested_attributes_for :phone_numbers, reject_if: :all_blank, allow_destroy: true

Netsted Attributes: PhoneNumber

class PhoneNumber < ApplicationRecord
  belongs_to :profile
end

3rd model: User

class User < ApplicationRecord
  has_one :profile
end

In database their relation is profile.user_id = user.id, phone_number.user_id = user.id

Question: How can I update Phone numbers when I update profile?

I tried

<%= form_for @profile, url: {action: "update"} do |f| %>
 ...
     <%= f.fields_for :phone_numbers do |ff| %>
       ...

and got error message:

Mysql2::Error: Unknown column 'phone_numbers.profile_id' in 'where clause': SELECT phone_numbers.* FROM phone_numbers WHERE phone_numbers.profile_id = 1


Solution

  • The errors is super clear and full of call to action:

    • add profile_id column to phone_numbers table to reflect the association between Profile and PhoneNumber models.