2012-11-10 1 views
0

내 응용 프로그램에 DwellingsRoomies이 있습니다. Dwelling보기에 일부 인증을 구축 중입니다. 현재 dwellingroomies은 특정 데이터를 볼 수 있어야합니다. 다른 모든 사용자는 다른보기를 볼 수 있습니다. users입니다.컨트롤러 Throwing에 정의 된 메서드 NoMethodError

이 기능을 활성화하려면 Users Controlleris_roomie? 메서드를 만들었습니다. 방법은 다음과 같습니다 : 다음과 같이

## is_roomie? method in Users_Controller.rb ## 

def is_roomie? 
roomie_ids = [] 
@dwelling.roomies.each do |r| 
    roomies_ids << r.id 
end 
roomie_ids.include?(current_user.id) 
end 

나는 Dwelling보기에서이 메서드를 호출 :이 구현 한 후 페이지를로드

## show.html.erb (Dwelling) ## 
.... 
<% if current_user && current_user.is_roomie? %> 
.... 

, 나는 다음과 같은 NoMethoderror 수 :

NoMethodError in Dwellings#show

Showing >/Volumes/UserData/Users/jraczak/Desktop/Everything/rails_projects/Roomie/roomie/app/views/dwellings/show.html.erb where line #5 raised:

undefined method `is_roomie?' for #User:0x00000102db4608>

일부 배경에서는 Dwelling 메서드로 시도했지만 User 모델로 옮겨서 사용할 수 없습니다. 모든 통찰력에 미리 감사드립니다!

답변

2

current_user 개체는 UsersController 개체가 아니기 때문에 User 개체가 아니므로 해당 개체에 대해 정의한 메서드를 호출 할 수 없습니다. 이런 맥락에서 생각하면 User에이 방법을 정의해야합니다. 하지만, 우리는 애플 리케이션/모델/dwelling.rb의 주거 클래스로 이동하여 코드를 향상시킬 수 있습니다,이 보면

class User < ActiveRecord::Base 
    # ... 
    def roomie?(dwelling) 
    dwelling.roomies.include?(self) 
    end 
end 

:

응용 프로그램/모델/user.rb에서이 같은 시도 :

class Dwelling < ActiveRecord::Base 
    # ... 
    def roomie?(user) 
    roomies.include?(user) 
    end 
end 
그런 다음에 뷰에서 이것을 사용하는 것이

:

<% if current_user && @dwelling.roomie?(current_user) %> 
+0

이것은 훌륭하게 작동합니다. 첫 번째 단락에 설명 된 실제 문제를 완전히 이해한다고 말하지는 않습니다. 즉, UsersController 객체가 무엇인지 이해하지 못합니다.하지만이를 읽으려고합니다. 내로드 블록을 수정 해 주셔서 감사합니다. – justinraczak

+0

users_controller.rb 맨 위에 컨트롤러가'class UsersController

0

CURRENT_USER 개체하지 않습니다 하 방법 is_roomie ?. 이것은 귀하의 컨트롤러에있는 방법입니다. 당신은 쇼 액션에서 메소드를 호출하여 다음과 같이 뷰에 사용할 수있게 할 수 있습니다.

#in UsersController.rb 
def show 
    @is_roomie = is_roomie? 
end