2013-10-21 2 views
1

레일 및 정규식을 처음 사용합니다. 사용자가 [email protected] 또는 [email protected]의 두 가지 유형의 전자 메일 주소 중 하나에 등록 할 수있는 응용 프로그램을 만들려고합니다. 나는 현재 사용자의 유형이 아닌 모든 사용자를 보여주는 페이지를 만들고 있습니다. 예를 들어 [email protected]가 로그인 한 경우 페이지에 b 유형의 모든 사용자가 표시됩니다. [email protected]가 로그인 한 경우 페이지에 a 유형의 모든 사용자가 표시됩니다. 정규식을 사용하여 전자 메일 주소를 기반으로 로그인 한 사용자 유형을 확인하고 사용자가 링크를 클릭 할 때 페이지를 동적으로 생성하려고합니다.이 레일즈 앱에서 정규 표현식을 사용하려면 어떻게해야합니까?

<% @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 %> 

보기 단순히 통해 루프 : 여기

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

각 사용자를 표시하는 도면이다 : I는 모델이 방법 만들었다 : 컨트롤러 다음

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

인 @user 개체. 페이지를로드하려고 할 때, 정의되지 않은 지역 변수 또는 메소드`current_user '가 있다고 들었습니다. 이 문제를 어떻게 해결할 수 있습니까?

답변

1

귀하의 모델은 도우미 방법을 인식하지 못합니다. Current_user는 그 중 하나입니다. 그래서 당신은 결과를 가져 오기 위해 현재 사용자 인스턴스를 사용/함수에 사용자 개체를 전달해야

# 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(/[email protected]\.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(/[email protected]\.edu/) 
     User.where("email NOT LIKE '%@a.edu'") 
    else 
     User.where('false') # workaround to returns an empty AR::Relation 
    end 
end 
+0

감사합니다. 대체 버전을 구현하려고했지만 이제는 정의되지 않은 메서드 인 'each'가 표시됩니다. 그건 내 말이 맞지 않아. 편집을하고 위의 질문 내용에보기를 넣었습니다. – Philip7899

+0

필자가 필자의 대답 @ Philip7899를 업데이트 한 것은 모델에서 렌더링을 시도했지만 컨트롤러에서 완료해야한다는 것입니다. – MrYoshiji

+0

감사합니다. 이제는 '작동하지 않는'렌더링이지만 실제로 작동해야하는 경우입니다. 내 정규식과 관련이 있다고 생각합니다. 내가 가진 정규식이 맞는지 알고 있니? – Philip7899

관련 문제