Rails – 从单独的设置控制器编辑用户和配置文件模型

我正在努力弄清楚如何让它工作,但基本上我有2个模型:

class User class Profile 

一个用户有一个配置文件。

我还有一个带有“配置文件”和“更新”操作的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_to @profile, notice: 'Profile was successfully updated.' } else format.html { render :edit } end end end private def profile_params params.require(:profile).permit(:name) end end 

和/ settings / profile页面:

 

Settings

Name:

我的路线:

 get 'settings/profile', to: 'settings#profile', as: :settings_profile post 'settings/profile', to: 'settings#update', as: :update_settings_profile 

如何获取我的表单(来自SettingsController)以允许我的用户和个人资料模型的字段?

*编辑

我已经覆盖了我的profile_path以从用户名中提取:

 def profile_path(profile) '/' + 'profiles' + '/' + profile.user.username end 

目前,当我加载包含表单的页面时,我收到此错误:

 wrong number of arguments (given 2, expected 1) 

当您将表单定义为<%= form_with(model: @profile, local: true) do |form| %> <%= form_with(model: @profile, local: true) do |form| %> ,它相当于

。 您需要告诉Rails将表单映射到自定义URL,就像这样

 <%= form_with(model: @profile, url: update_settings_profile_path, local: true) 

您需要在profile_params中将usernamesurname 列入白名单 ,以反映数据库中的更改。

 def profile_params params.require(:profile).permit(:username, surname) end