http://ruby.railstutorial.org/ruby-on-rails-tutorial-bookに基づいてRails3.1を使用し、RailsCast 274(http://railscasts.com / episodes / 274-remember-me-reset-password)。したがって、Railsアプリにセッション管理用のcurrent_userがあります。これは次のようになります。
def current_user
@current_user ||= User.find_by_auth_token!(cookies[:auth_token]) if cookies[:auth_token]
end
このユーザーの2つの値を確認したいという問題があります。
私のユーザーモデルは次のようになります。
# == 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+\-.]+@[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
確認したい値は、trueかどうかに関係なく、:adminと:writerです。ご覧のとおり、これらの値を編集できるのは管理者だけであるため、アクセス可能としてマークされていません。RailsCast 237のようにこれを解決します(リンクを挿入したいのですが、新しいユーザーとして3つ以上のリンクを投稿することは許可されていません)。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'
この問題が解決できるかどうか、そしてどのように解決できるか誰かに教えてもらえますか?よろしくお願いします!
更新1:current_user.adminがわかりましたか?またはcurrent_user.writer?コントローラでも動作しません。ですから、そのための一般的なヘルパーメソッドが必要なようです。