Rails 4 form_for error: undefined method `model_na

2019-06-03 23:33发布

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

In the controller:

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

Here's my routes:

  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'

2条回答
Fickle 薄情
2楼-- · 2019-06-03 23:59
Extracted source (around line #6):
  <%= form_for @user, url: {action: "create_user"}, html: {class: "user-create-form"} do |f| %>

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

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

Change your code like this:

def create_user
  @user = User.new
end
查看更多
劫难
3楼-- · 2019-06-04 00:20

The create_user requires params[:user'] to function and so there is no need to check for params. A simple modification:

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

Why would you then pass User.new if params are not present? create_user should be a post only route. You require User.new(params[:user]) because if validation fails, you'll pass that object back to the form with errors and existing input.

Change your routes here:

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

Then create a new method in your controller for new_user:

def new_user
  @user = User.new
end

You're also building your routes in the wrong way. Use resources:

namespace :admin do
  resources :user
end

See this guide for more information.

查看更多
登录 后发表回答