简体   繁体   中英

rails form helper change form text_field

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 ?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM