【问题标题】:Rails - Editing User and Profile Models from separate Settings ControllerRails - 从单独的设置控制器编辑用户和配置文件模型
【发布时间】: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) 方法。不管怎样,你试过&lt;%= form_with(model: @profile, local: true, url: update_settings_profile_path) do |form| %&gt;吗?它应该工作。如果要保存usernamesurname,则需要将profile_params 中的那些列入白名单,例如params.require(:profile).permit(:username,:surname)

标签: ruby-on-rails forms controller routes ruby-on-rails-5


【解决方案1】:

当您将表单定义为&lt;%= form_with(model: @profile, local: true) do |form| %&gt; 时,它相当于&lt;form action="/profiles/1" method="post" data-remote="false"&gt;。您需要告诉 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

【讨论】:

  • 这立即奏效 - 没有意识到可以使用 form_with 设置模型和 url,非常感谢您的帮助!
  • 请问,该表单目前不接受我的 User 模型的任何字段 - 扩展我的表单和控制器以允许来自两个/任一模型的字段的最佳方法是什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-14
  • 2020-07-03
  • 2011-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-14
相关资源
最近更新 更多