2012-11-10 68 views
0

我的應用程序有DwellingsRoomies。我正在建立一些認證到Dwelling視圖 - 只有users誰是當前dwellingroomies應該能夠查看某些數據 - 所有其他用戶將看到不同的視圖。控制器投擲方法定義NoMethodError

爲了實現這個功能,我在Users Controller中創建了一個is_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_userUser對象,而不是UsersController對象,因此您無法調用您在該對象上定義的方法。當你在這種情況下思考它時,你會發現你應該在User上定義這個方法。

嘗試在app /模型/ user.rb是這樣的:

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

望着這一點,雖然,我們可以通過移動入在app /模型/ dwelling.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 
相關問題