Rails 4 form_for 错误:ActionController::Parameters:Class 的未定义方法`model_name' [英] Rails 4 form_for error: undefined method `model_name' for ActionController::Parameters:Class

查看:40
本文介绍了Rails 4 form_for 错误:ActionController::Parameters:Class 的未定义方法`model_name'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to make a basic form for creating a user record:

<%= 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

这可以正常加载并且没有错误,但是当我提交表单时,出现以下错误:

This loads fine and without error, but when I submit the form, I get the following error:

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'

推荐答案

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

form_for 接受 ActiveRecord 类的对象.但是您在 create_user 操作中的控制器中犯了一个错误.

form_for accepts object of ActiveRecord class. But you have made a mistake in controller in create_user action.

create_user 操作中的@user 变量不是 active_record 的对象,因为您正在为其分配 params[:user] 哈希值.

@user variable in create_user action is not an object of active_record because you are assigning params[:user] hash to that.

像这样改变你的代码:

def create_user
  @user = User.new
end

这篇关于Rails 4 form_for 错误:ActionController::Parameters:Class 的未定义方法`model_name'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆