1

我正在尝试制作用于创建用户记录的基本表单:

<%= debug(@user) %>
<%= form_for @user, url: {action: "create_user"}, html: {class: "user-create-form"} do |f| %>
    <div class="form-group"><%= f.text_field :first_name, class:'form-control' %></div>
    <div class="form-group"><%= f.text_field :last_name, class:'form-control' %></div>
    <div class="form-group"><%= f.text_field :email, class:'form-control' %></div>
    <div class="form-group"><%= f.text_field :password, class:'form-control' %></div>
    <%= f.submit "Update" %>
<% end %>

在控制器中:

  def create_user
    @user = params[:user]
    @user = User.new if !@user
  end

这加载正常且没有错误,但是当我提交表单时,我收到以下错误:

NoMethodError in Admin#create_user

Showing /Applications/MAMP/htdocs/clippo2/app/views/admin/create_user.html.erb where line #6 raised:

undefined method `model_name' for ActionController::Parameters:Class

Extracted source (around line #6):
  <%= form_for @user, url: {action: "create_user"}, html: {class: "user-create-form"} do |f| %>

这是我的路线:

  get "admin", to: "admin#index"
  get "admin/edit_user/:id", to: "admin#edit_user"
  patch "admin/edit_user/:id", to: "admin#edit_user"
  get "admin/create_user"
  post "admin/create_user"
  get "admin/delete_user"
  get "access/login"
  get "access/logout"
  post "access/attempt_login"

  root :to => 'pages#home'
4

2 回答 2

1
Extracted source (around line #6):
  <%= form_for @user, url: {action: "create_user"}, html: {class: "user-create-form"} do |f| %>

form_for接受ActiveRecord类的对象。但是你在控制器中犯了一个错误create_user

实际中的@user 变量create_user不是对象,active_record因为您正在params[:user]为其分配哈希。

像这样更改您的代码:

def create_user
  @user = User.new
end
于 2013-08-28T18:32:35.787 回答
0

create_user需要功能,因此params[:user']无需检查参数。一个简单的修改:

def create_user
  @user = User.new(params[:user])
end

User.new如果参数不存在,你为什么会通过?create_user应该是仅发布的路线。您需要User.new(params[:user]),因为如果验证失败,您将将该对象传递回带有错误和现有输入的表单。

在此处更改路线:

  get "admin/create_user" => get "admin/new_user"

然后在您的控制器中创建一个新方法new_user

def new_user
  @user = User.new
end

您还以错误的方式构建路线。使用资源:

namespace :admin do
  resources :user
end

有关更多信息,请参阅本指南

于 2013-08-28T18:37:21.933 回答