Rails-从单独的Settings Controller编辑用户和个人资料模型 [英] Rails - Editing User and Profile Models from separate Settings Controller
问题描述
我正在努力弄清楚究竟该如何工作,但实际上我有2种模型:
I'm struggling to figure out exactly how to get this to work, but essentially I have 2 models:
class User
class Profile
一个用户有一个个人资料。
One User has One Profile.
我还有一个带有配置文件和更新操作的SettingsController:
I also have a SettingsController with "profile" and "update" actions:
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页面:
And the /settings/profile page:
<h1>Settings</h1>
<div>
<div>
Name: <%= @profile.name %>
</div>
<%= form_with(model: @profile, local: true) do |form| %>
<div class="field">
<%= form.label :username %>
<%= form.text_field :username %>
</div>
<div class="field">
<%= form.label :surname %>
<%= form.text_field :surname %>
</div>
<div class="actions">
<%= form.submit %>
</div>
<% end %>
</div>
我的路线:
get 'settings/profile', to: 'settings#profile', as: :settings_profile
post 'settings/profile', to: 'settings#update', as: :update_settings_profile
如何(从SettingsController)获取表单以允许用户和个人资料模型使用字段?
How can I get my form (from SettingsController) to allow fields for my User and Profile models?
*编辑
我已经覆盖了我的profile_path以从用户名中提取:
I have overridden my profile_path to pull from the username:
def profile_path(profile)
'/' + 'profiles' + '/' + profile.user.username
end
当前,当我加载包含表单的页面时,出现以下错误:
Currently, when I load the page containing the form, I get this error:
wrong number of arguments (given 2, expected 1)
推荐答案
当您将表单定义为<%= form_with(model:@profile,local:true)时| form | %>
,它等效于< form action = / profiles / 1 method = post data-remote = false>
。您需要像这样使Rails将表单映射到自定义网址
When you define the form as <%= form_with(model: @profile, local: true) do |form| %>
, it is equivalent to <form action="/profiles/1" method="post" data-remote="false">
. You need to tell Rails to map the form to the custom url like so
<%= form_with(model: @profile, url: update_settings_profile_path, local: true)
您需要 profile_params 白名单 用户名
和姓氏
>以便反映数据库中的更改。
And you need to whitelist username
and surname
in the profile_params
in order to reflect the changes in the DB.
def profile_params
params.require(:profile).permit(:username, surname)
end
这篇关于Rails-从单独的Settings Controller编辑用户和个人资料模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!