Reputation: 131
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
.* FROMphone_numbers
WHEREphone_numbers
.profile_id
= 1
Upvotes: 0
Views: 439
Reputation: 1428
To add the profile_id
column to phone_numbers
table you need a migration. That is performed using the rails command as follows:
rails generate migration AddProfileRefToPhoneNumbers profile:references
rake db:migrate
This will fix your problem with your error. I can also see down the line you will have an issue with:
class User < ApplicationRecord
has_one :profile
end
class Profile < ApplicationRecord
belongs_to :account
Your profile belongs_to account, not user. You want to replace account with user or replace your foreign key with account_id and change the line to:
belongs_to :account, class_name: 'User'
Upvotes: 2
Reputation: 52357
The errors is super clear and full of call to action:
profile_id
column to phone_numbers
table to reflect the association between Profile
and PhoneNumber
models.Upvotes: 2