在我更改视图布局之前,Rails正确显示我的登录视图。 但是在更改之后,我在下面收到了一条错误消息。
NilClass的未定义方法`model_name':Class
改变之前, “app / views / layouts / application.html.erb”已应用于我的登录视图。
我只想在登录视图中更改布局。 所以,“我制作了app / views / layouts / login.html.erb”并在控制器上放了一些代码。 def登录 render:layout => '登录' 端
我猜错误必须来自代码,其中包括@member。
{:action => 'login'})do | f | %GT;但我不明白为什么。你能给我一些建议吗?
☆会员控制器
def login
render :layout =>'login'
@msg = "get"
@member = Member.new
if request.post? then
@member = Member.new(params[:member])
record = Member.find_by_user(params[:member][:user])
if record == nil then
@msg = "record is nil."
@member.errors.add('user',"not registrated!")
else
if record.pass != params[:member][:pass] then
@msg = "password is wrong."
@member.errors.add('pass','password is wrong!')
else
@msg = "good!"
@member = record
session[:login] = record
redirect_to '/members/' + record.id.to_s
end
end
end
端
☆布局/ login.html.erb
<!DOCTYPE html>
<html>
<head>
<title>XXXX</title>
<%= stylesheet_link_tag "application", media: "all" %>
<%= javascript_include_tag "application" %>
<%= csrf_meta_tags %>
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<%= render 'layouts/exheader'%>
<div class= "container">
<%= yield %>
</div>
<div class="container">
<%= render 'layouts/footer' %>
</div>
</body>
</html>
☆login.html.erb(成员)
<div class="span4">
<div class="login_form">
<h4>Login</h4>
<%= form_for(@member, :url => {:action => 'login'}) do |f| %>
<% if @member.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@member.errors.count, "error")%>
prohibited this member from being saved:</h2>
<ul>
<% @member.errors.full_messages.each do |msg| %>
<li><%=msg %></li>
<% end %><%# do |msg|%>
</ul>
</div>
<% end %><%# if%>
<div class="field">
<%= f.label :user %>
<%= f.text_field :user %>
</div>
<div class="field">
<%= f.label :pass %>
<%= f.password_field :pass %>
</div>
<div class="actions">
<%= f.submit :value => "login" %>
</div>
<% end %><%# do |f|%>
</div><!-- login form -->
</div><!--span4 for login -->
答案 0 :(得分:1)
当发生render
时,Rails会立即开始渲染视图。所以在你的代码中,你已经在动作的最开始放置了render :layout => 'login'
,因此在执行任何动作代码之前渲染了视图;因此,所有实例变量(如@member
和@msg
)尚未声明,在呈现视图时它们的值为nil
。所以
<%= form_for(@member, :url => {:action => 'login'}) do |f| %>
<%# if @member.errors.any? %>
抱怨@member
,nil
,没有方法model_name
。
最终,您只应将render
放在控制器代码的末尾。也许是这样的:
def login
@msg = "get"
@member = Member.new
if request.post?
@member = Member.new(params[:member])
record = Member.find_by_user(params[:member][:user])
if record.nil?
@msg = "record is nil."
@member.errors.add('user',"not registrated!")
else
if record.pass != params[:member][:pass]
@msg = "password is wrong."
@member.errors.add('pass','password is wrong!')
else
@msg = "good!"
@member = record
session[:login] = record
redirect_to '/members/' + record.id.to_s
return
end
end
end
render :layout =>'login'
end