问题
When I click the edit I get: First argument in form cannot contain nil or be empty in bets/app/views/users/_form.html.erb
users/_form
<%= form_for(@user) do |f| %>
<% if @user.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@user.errors.count, "error") %>
prohibited this user from being saved:</h2>
<ul>
<% @user.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<p>
<%= f.label :name, "Username" %><br />
<%= f.text_field :name %>
</p>
<p>
<%= f.label :email %><br />
<%= f.text_field :email %>
</p>
<p>
<%= f.label :password %><br />
<%= f.password_field :password %>
</p>
<p>
<%= f.label :password_confirmation %><br />
<%= f.password_field :password_confirmation %>
</p>
<% if @user.new_record? %>
<%= f.submit "Sign up" %>
<% else %>
<%= f.submit "Update Profile" %>
<% end %>
<% end %>
in users_controller
class UsersController < ApplicationController
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
flash[:notice] = "You have signed up successfully."
redirect_to posts_path
else
render :new
end
end
def show
@user=User.find(params[:id])
end
def update
if @user.update(user_params)
flash[:notice] = "Profile has been updated"
redirect_to @user
else
flash[:alert] = "Profile has not been updated"
render 'edit'
end
end
def edit
end
def destroy
@user = User.find(params[:id])
@user.destroy
flash[:notice] = "Post has been destroyed."
redirect_to posts_path
end
private
def user_params
params.require(:user).permit(:name,:password,:password_confirmation, :email)
end
end
in model user
class User < ActiveRecord::Base
has_secure_password
end
in view/edit
<h2>Edit Profile</h2>
<%= render 'form' %>
in view/show
<h1>Profile Page for <%= @user.name %></h1>
<p>Email: <%= @user.email %></p>
<p><%= link_to "Edit Profile", edit_user_path(@user) %></p>
<%= link_to "Delete Profile",user_path(@user),method: :delete,
data: { confirm:"Are you sure you want to delete this post?"} %>
What is the problem and how can I fix it? p.s.: is rails 4
回答1:
You should set @user
instance variable in edit
action:
def edit
@user = User.find(params[:id])
end
The reason you have this error is you pass @user
instance variable as argument to form_for
. This variable evaluates to nil
, since you don't set it in your edit
action.
BTW, you have similar bug in update
action - I'm quite sure it will crash (with "undefined method update
for nil
") if you call it. You should insert line
@user = User.find(params[:id])
on the top of update
action.
来源:https://stackoverflow.com/questions/19809889/ror4-first-argument-in-form-cannot-contain-nil-or-be-empty