1

私はレールと正規表現が初めてです。ユーザーが 2 種類のメール アドレス (user@a.edu または user@b.edu) のいずれかで登録できるアプリケーションを作成しようとしています。現在のユーザーのタイプではないすべてのユーザーを表示するページを作成しています。たとえば、jason@a.edu がログインした場合、ページにはタイプ b のすべてのユーザーが表示されます。lauren@b.edu がログインしている場合、ページにはタイプ a のすべてのユーザーが表示されます。正規表現を使用して、電子メール アドレスに基づいてログインしているユーザーのタイプを把握し、ユーザーがリンクをクリックしたときにページを動的に生成しようとしています。モデルでこのメソッドを作成しました:

def other_schools
   if /.+@a\.edu/.match(current_user.email)
      User.where(email != /.+@a\.edu/)
   else
      render :text => 'NOT WORKING', :status => :unauthorized
   end
end

コントローラーは次のとおりです。

def index
    #authorize! :index, :static_pages 
    @users = current_user.other_schools
end

各ユーザーを表示するビューは次のとおりです。

<% @users.each do |user| %>
          <li class="span3">
                <div class="thumbnail" style="background: white;">
                  <%= image_tag "idea.jpeg" %>
                  <h3><%= user.role %></h3>
                  <p>Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec id elit non mi porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit.</p>
                  <a class="btn btn-primary">View</a>
                </div>
          </li>
<% end %>

ビューは @user オブジェクトを単純にループします。ページを読み込もうとすると、未定義のローカル変数またはメソッド「current_user」があると言われます。これを修正するにはどうすればよいですか?

4

1 に答える 1

1

モデルはヘルパー メソッドを「認識」していません。Current_user はその 1 つです。そのため、ユーザー オブジェクトを関数に渡すか、現在のユーザー インスタンスを使用して結果をフェッチする必要があります。

# controller
def index
    #authorize! :index, :static_pages
    @users = User.other_schools(current_user)
end

# User model
def self.other_schools(user) # class method
   if user.email.match(/.+@a\.edu/)
      User.where("email NOT LIKE '%@a.edu'")
   else
      User.where('false') # workaround to returns an empty AR::Relation
   end
end

代替 (current_user インスタンスを使用):

# controller
def index
    #authorize! :index, :static_pages
    @users = current_user.other_schools
    if @users.blank?
        render :text => 'NOT WORKING', :status => :unauthorized
    end
end

# User model
def other_schools # instance method
   if self.email.match(/.+@a\.edu/)
      User.where("email NOT LIKE '%@a.edu'")
   else
      User.where('false') # workaround to returns an empty AR::Relation
   end
end
于 2013-10-21T17:48:35.393 に答える