2012-11-10 76 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 
相关问题