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'
form_for
accepts object ofActiveRecord
class. But you have made a mistake in controller increate_user
action.@user variable in
create_user
action is not an object ofactive_record
because you are assigningparams[:user]
hash to that.Change your code like this:
The
create_user
requiresparams[:user']
to function and so there is no need to check for params. A simple modification:Why would you then pass
User.new
if params are not present?create_user
should be a post only route. You requireUser.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:
Then create a new method in your controller for
new_user
:You're also building your routes in the wrong way. Use resources:
See this guide for more information.