Rails-从单独的Settings Controller编辑用户和个人资料模型

时间:2018-09-24 04:06:35

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

我正在努力弄清楚如何使它正常工作,但实际上我有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)

1 个答案:

答案 0 :(得分:1)

将表单定义为<%= form_with(model: @profile, local: true) do |form| %>时,它等效于<form action="/profiles/1" method="post" data-remote="false">。您需要像这样使Rails将表单映射到自定义网址

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

并且您需要在username中将白名单 surnameprofile_params列入白名单,以反映数据库中的更改。

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