【发布时间】:2019-02-27 13:35:15
【问题描述】:
我正在努力弄清楚如何让它发挥作用,但基本上我有 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 页面:
<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)允许我的用户和配置文件模型的字段?
*编辑
我已经覆盖了我的 profile_path 以从用户名中提取:
def profile_path(profile)
'/' + 'profiles' + '/' + profile.user.username
end
目前,当我加载包含表单的页面时,我收到此错误:
wrong number of arguments (given 2, expected 1)
【问题讨论】:
-
问题是什么?
-
已编辑原始问题 - 如何获取我的表单(来自 SettingsController)以允许我的用户和配置文件模型的字段?
-
您的代码看起来不错。提交表单时会发生什么?
-
@Pavan 在我原来的问题中添加了一些额外的代码。目前,如果不解决这个问题,我什至无法加载页面本身。我发现我可以通过将表单从“form_with(model:@profile)”更改为“form_with(url:settings_profile_path)”来修复错误,但是从这里表单不会保存任何数据。
-
我不明白你为什么定义
profile_path(profile)方法。不管怎样,你试过<%= form_with(model: @profile, local: true, url: update_settings_profile_path) do |form| %>吗?它应该工作。如果要保存username和surname,则需要将profile_params中的那些列入白名单,例如params.require(:profile).permit(:username,:surname)
标签: ruby-on-rails forms controller routes ruby-on-rails-5