这是原始问题的扩展:Rails - Editing User and Profile Models from separate Settings Controller
我的表单非常适合编辑单个模型(配置文件),但是我尝试将其扩展为还允许用户编辑User模型中的某些字段。当前,整个表单不再保存任何数据-但是我的浏览器中没有看到任何可见的错误消息,除了更新方法中的“成功”消息没有触发。
如何成功扩展此设置,以允许用户和个人资料字段以相同的形式保存?表单当前正在编辑配置文件,然后允许用户使用fields_-这是错误的方法吗?
我有2个模型,用户:
updateCount() {
this.setState((prevState, props) => {
return { top: prevState.top + 1 }
});
this.updateCountTimer = setTimeout(()=> this.updateCount(), this.state.timeoutValue)
}
componentWillUnMount(){
clearTimeout(this.updateCountTimer);
}
和个人资料:
class User < ApplicationRecord
has_one :profile, dependent: :destroy
before_create :create_profile
private
def create_profile
build_profile(name: username)
end
end
两个模型都可以通过SettingsController进行编辑:
class Profile < ApplicationRecord
belongs_to :user
accepts_nested_attributes_for :user
end
在设置/个人资料上,用户的个人资料可以通过以下格式进行编辑:
class SettingsController < ApplicationController
def profile
@profile = User.find_by_id(current_user).profile
end
def update
set_profile
respond_to do |format|
if @profile.update(profile_params)
format.html { redirect_back fallback_location: settings_path, notice: 'Profile was successfully updated.' }
else
format.html { render :edit }
end
end
end
private
def profile_params
params.require(:profile).permit(:name, user_attributes: [:email])
end
end
这是显示配置文件页面的路由列表,以及所有其他方法的更新方法:
<h1>Settings</h1>
<div>
<div>
Name: <%= @profile.name %>
</div>
<%= form_with(model: @profile, url: update_settings_profile_path, local: true) do |form| %>
<div class="field">
<%= form.label :name %>
<%= form.text_field :name %>
</div>
<%= form.fields_for :user do |user_form| %>
<div class="field">
<%= user_form.label :email %>
<%= user_form.text_field :email %>
</div>
<% end %>
<div class="actions">
<%= form.submit %>
</div>
<% end %>
</div>
提交表单时的参数:(为清楚起见,删除了身份验证令牌。)
get 'settings', to: redirect('settings/profile')
get 'settings/profile', to: 'settings#profile', as: :settings_profile
patch 'settings', to: 'settings#update', as: :update_settings
模式:(为清楚起见,删除了基本列。)
Parameters: {"utf8"=>"✓", "authenticity_token"=>"X", "profile"=>{"name"=>"John Doe", "user_attributes"=>{"email"=>"test@email.com", "id"=>"22"}}, "commit"=>"Update Profile"}
感谢任何提示!