我目前有以下型号:
user.rb
class User < ApplicationRecord
has_one :profile, dependent: :destroy
before_create :build_profile
end
profile.rb
class Profile < ApplicationRecord
belongs_to :user
delegate :name, :email, :name=, :email=, to: :user
end
对于个人资料,我有以下控制器:
profile_controller.rb
class ProfileController < ApplicationController
before_action :set_user
before_action :authenticate_user!
def edit
@user = current_user
@profile = @user.profile
end
def update
@user = current_user
@profile = @user.profile
if @profile.update(profile_params)
redirect_to profile_path(current_user.username)
else
render :edit
end
end
private
def profile_params
params.require(:profile).permit(:name, :email, :user_id, :bio, :avatar, :remove_avatar)
end
end
我的“编辑个人资料”表单如下:
edit.html.haml
= simple_form_for @profile do |f|
= f.error_notification
.form-inputs
.row
.col-md-6.col-sm-12
= f.input :name, required: true, placeholder: "Name"
.col-md-6.col-sm-12
= f.input :email, required: true, placeholder: "Email"
= f.input :bio, required: true, hint: "Write a short bio about yourself", placeholder: "PHP Developer developing cool apps in Tokyo."
= f.input :avatar, as: :attachment, direct: true, presigned: true
.form-actions
= f.button :submit, "Update", class: "btn ban-info"
我正在尝试更改配置文件表单中的委托值。但是,它们不会持久存储到数据库中。我该怎么做呢?
由于
答案 0 :(得分:1)
代替通常为暴露不涉及持久性的公共方法而保留的委托,请尝试将以下行添加到配置文件模型中:
accepts_nested_attributes_for :user #This will allow you to handle user attributes via a profile object
此外,在您的update
操作中,您需要指定个人资料和用户的关系,例如:
if @user.profile.update_attributes(profile_params)