Reputation: 27
I have a User model that defines an has_one :profile
association.
On the user edit action/page I update the user attributes. I would like to update an attribute that does not belong to the User model but to the Profile one.
This is my view :
# _form.html.haml
=f.text_field :phone
Using this form, how could I also update the phone
attribute of @user.profile
?
Upvotes: 0
Views: 269
Reputation: 5474
You should allow update of nested attributes in your User model :
class User
has_one :profile
accepts_nested_attributes_for :profile
end
Then in your form use the fields_for
method to nest fields from Profile into the User form :
= f.fields_for :profile do |p|
= p.text_field :phone
Upvotes: 1
Reputation: 23356
As a general idea if you have two tables user and profile with associations then -
User table = id, first_name, last_name
Profile table = id, user_id, phone
Associations:
User Class
-
class User < ActiveRecord::Base
has_one :profile
end
Profile Class
-
class Profile < ActiveRecord::Base
belongs_to :user
end
User Controller
-
def index
@user = current_user
@user_phone = @user.profile.phone
end
Upvotes: 0