我已經使用基於http://ruby.railstutorial.org/ruby-on-rails-tutorial-book的Rails 3.1和RailsCast 274(http://railscasts.com/episodes/274-remember-me-reset-password)中提供的授權構建了我自己的基本博客工具。所以,我有我的會話管理CURRENT_USER在我的Rails應用程序,如下所示:Rails 3.1助手方法來檢查current_user的值
def current_user
@current_user ||= User.find_by_auth_token!(cookies[:auth_token]) if cookies[:auth_token]
end
現在我有這個問題,我想檢查該用戶的兩個值。
我的用戶模型是這樣的:
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# name :string(255)
# email :string(255)
# password_digest :string(255)
# admin :boolean default(FALSE)
# created_at :datetime
# updated_at :datetime
# auth_token :string(255)
# writer :boolean default(FALSE)
# website :string(255)
#
class User < ActiveRecord::Base
attr_accessible :name, :email, :website, :password, :password_confirmation
has_secure_password
has_many :articles, :dependent => :destroy
email_regex = /\A[\w+\-.][email protected][a-z\d\-.]+\.[a-z]+\z/i
website_regex = /(^$)|(^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$)/ix
validates :name, :presence => true,
:length => { :maximum => 50 }
validates :email, :presence => true,
:format => { :with => email_regex },
:uniqueness => { :case_sensitive => false }
# Automatically create the virtual attribute 'password_confirmation'.
validates :password, :presence => true,
:confirmation => true,
:length => { :within => 6..40 }
validates :website, :format => { :with => website_regex }
before_create { generate_token(:auth_token) }
private
def generate_token(column)
begin
self[column] = SecureRandom.urlsafe_base64
end while User.exists?(column => self[column])
end
end
我要檢查的值是:管理員和:作家,如果他們是真的還是假的。正如您所看到的,它們沒有被標記爲可訪問,因爲我希望只有管理員可以編輯這些值。我在RailsCast 237中解決了這個問題(我想插入鏈接,但我不允許作爲新用戶發佈兩個以上的鏈接)。使用current_user.admin在控制器中檢查這些參數?或current_user.writer?似乎沒有問題。但是,如果在一個視圖中我得到以下錯誤消息試試這個:
ActionView::Template::Error (undefined method `writer' for nil:NilClass):
15: <li><%= link_to "Log in", signin_path %></li>
16: <% end %>
17: </ul>
18: <% if current_user.writer == true %>
19: <ul>
20: <li><%= link_to "new article", newarticle_path %></li>
21: </ul>
app/views/layouts/_header.html.erb:18:in `_app_views_layouts__header_html_erb___3376819447841576130_36475600'
app/views/layouts/application.html.erb:12:in `_app_views_layouts_application_html_erb__676755681270806253_35068900'
請能有人告訴我,如果這個問題是可以解決的,如何?非常感謝!我想通了,current_user.admin?或current_user.writer?也不能在控制器中工作。所以看來我需要一個通用的輔助方法。
非常感謝你,是解決我的問題! –