我跟踪了官方授权教程,但出了点事。
我成功地创建了一个用户,但是当我尝试show他的配置文件页面时,我得到了以下错误:
undefined method `email' for #<UserSession: {:unauthorized_record=>"<protected>"}>以下是相关代码:
# user.rb
class User < ActiveRecord::Base
acts_as_authentic do |c|
c.crypto_provider = Authlogic::CryptoProviders::BCrypt
c.require_password_confirmation(false)
end
attr_accessible :username, :email, :password
end
# users_controller.rb
def show
@user = @current_user
end
# application_controller.rb
private
def current_user_session
return @current_user_session if defined?(@current_user_session)
@current_user_session = UserSession.find
end
def current_user
return @current_user if defined?(@current_user)
@current_user = current_user_session and current_user_session.user
end我想那是整个链条。以下是我们的看法:
# views/users/show.html.erb
<%=h @user.username%>
email: <%=h @user.email %>
<%= link_to "Edit", edit_account_path %>当我删除“电子邮件”行时,我会得到一个只有“编辑”链接的页面。用户名不出现。但是,当我添加<%= debug @user %>以查看正在发生什么时,它正确地打印存储在数据库中的email和username的值。我不知道为什么它不打印@user.username,为什么当我试图打印@user.email时它会抛出一个错误。
应该注意的是,show.html.erb 教程的布局使用@user.login,并且工作正常。我刚把“登录”改为“用户名”。
此外,当我单击“编辑”时,我会得到相同的原始错误:
undefined method `email' for #<UserSession: {:unauthorized_record=>"<protected>"}>下面是edit布局和部分使用的表单:
# views/users/edit.html.erb
<h1>Edit My Account</h1>
<% form_for @user, :url => account_path do |f| %>
<%= f.error_messages %>
<%= render :partial => "form", :object => f %>
<%= f.submit "Update" %>
<% end %>
<br />
<%= link_to "My Profile", account_path %>
#views/users/_form.erb
<%= form.label :username %><br />
<%= form.text_field :username %><br />
<br />
<%= form.label :email %><br />
<%= form.text_field :email %><br />
<br />
<%= form.label :password, form.object.new_record? ? nil : "Change password" %><br />
<%= form.password_field :password %><br />
<br />同样,所有这些都是从本教程中逐字提取的,这只是起作用而已。
我正在运行Rails 2.3.2和最新的Authlogic (今天刚刚安装,不管是什么版本),据我疲惫和沮丧的大脑所知,我确实在数据库和它们拼写正确中拥有所有必需的字段。
,怎么回事?
发布于 2010-02-11 07:50:57
,好吧,这太让…难堪了
结果发现问题是我对自然语言的偏爱。下面是本教程中列出的current_user方法:
def current_user
return @current_user if defined?(@current_user)
@current_user = current_user_session && current_user_session.user
end但是,在将其应用于我的情况时,我将&&替换为and,而结果 current_user_session.user没有被考虑在内。这就是为什么它一直在说UserSession这个和那个。我觉得很奇怪,但我看不出它是从哪里来的。现在我知道了。
发布于 2011-03-10 20:31:35
现在你可以代替
UserSession.create u至
UserSession.create :email => u.email, :password => u.password没什么大不了的。
但那让我感到另一种感觉。我忘了我的用户在创建时激活了?== false。我已将其设置为true,并创建了会话。
发布于 2010-02-11 07:30:35
我认为您希望有以下代码:
# users_controller.rb
def show
@user = current_user
end注意,current_user实际上是一个方法,而不是实例变量@current_user。
https://stackoverflow.com/questions/2242871
复制相似问题