関連を定義する User モデルがありますhas_one :profile
。
ユーザー編集アクション/ページで、ユーザー属性を更新します。UserモデルではなくProfileモデルに属している属性を更新したいと考えています。
これは私の見解です:
# _form.html.haml
=f.text_field :phone
このフォームを使用して、どうすれば のphone
属性も更新できます@user.profile
か?
関連を定義する User モデルがありますhas_one :profile
。
ユーザー編集アクション/ページで、ユーザー属性を更新します。UserモデルではなくProfileモデルに属している属性を更新したいと考えています。
これは私の見解です:
# _form.html.haml
=f.text_field :phone
このフォームを使用して、どうすれば のphone
属性も更新できます@user.profile
か?
ユーザーモデルのネストされた属性の更新を許可する必要があります。
class User
has_one :profile
accepts_nested_attributes_for :profile
end
次に、フォームでこのfields_for
メソッドを使用して、プロファイルのフィールドをユーザーフォームにネストします。
= f.fields_for :profile do |p|
= p.text_field :phone
2 つのテーブル user と profile が関連付けられている場合の一般的な考え方として、次のようになります。
ユーザー テーブル = id、first_name、last_name
プロファイル テーブル = id、user_id、電話
協会:
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