ruby-on-rails - Rails - 从单独的控制器和表单编辑多个模型
问题描述
这是这个原始问题的扩展:Rails - Editing User and Profile Models from separate Settings Controller
我的表单非常适合编辑单个模型(配置文件),但是我试图扩展它以允许用户编辑用户模型中的一些字段。目前,整个表单不再保存任何数据 - 但我没有在浏览器中看到任何可见的错误消息,除了我的更新方法中的“成功”消息没有触发。
如何成功扩展此设置以允许将 User 和 Profile 字段保存在同一表单中?该表单当前编辑个人资料,然后允许 fields_for 用户 - 这是错误的方式吗?
我有 2 个模型,用户:
class User < ApplicationRecord
has_one :profile, dependent: :destroy
before_create :create_profile
private
def create_profile
build_profile(name: username)
end
end
和简介:
class Profile < ApplicationRecord
belongs_to :user
accepts_nested_attributes_for :user
end
两种模型都可以通过 SettingsController 进行编辑:
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"}
架构:(为清楚起见,删除了基本列。)
create_table "profiles", force: :cascade do |t|
t.string "name"
t.bigint "user_id"
...
t.index ["user_id"], name: "index_profiles_on_user_id"
end
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "username", default: "", null: false
...
end
感谢任何提示!
解决方案
推荐阅读
- database - Angular:从 API 检索的数据仅在应用首次启动时出现
- sql - Microsoft SQL Server:仅返回每个唯一 ID 具有最近日期的行
- ios - 设置 UIButton 大小以显示在情节提要上
- ruby-on-rails - webpack 服务器实时重载
- ios - 如何在模态呈现的表单 UIViewController 内为 UIScrollView 计算正确的键盘 contentInset
- python - braidTool_Maya_script_error # NameError: name 'QtGui' is not defined
- c - 试图理解 C 中的递归
- c++ - 使用 set-width 对齐列
- python - 通过wifi在两个系统上的两个python脚本之间进行通信
- python - 无法让我的程序返回主循环