【问题标题】:Method Defined in Controller Throwing NoMethodError控制器中定义的方法抛出 NoMethodError
【发布时间】:2012-11-10 21:18:47
【问题描述】:

我的应用程序有DwellingsRoomies。我正在 Dwelling 视图中构建一些身份验证 - 只有当前 roomiesusers dwelling 应该能够查看某些数据 - 所有其他用户将看到不同的视图。

为了实现这一点,我在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#show

显示 >/Volumes/UserData/Users/jraczak/Desktop/Everything/rails_projects/Roomie/roomie/app/views/dwellings/show.html.erb 其中第 5 行出现:

未定义的方法`is_roomie?'对于#User:0x00000102db4608>

对于某些背景,我确实尝试过将此作为Dwelling 方法并将其移至User 模型中,但无济于事。提前感谢您提供任何和所有见解!

【问题讨论】:

    标签: ruby-on-rails methods nomethoderror


    【解决方案1】:

    current_userUser 对象,而不是UsersController 对象,因此您不能调用您在该对象上定义的方法。当您在这种情况下考虑它时,您会发现您应该在User 上定义此方法。

    在 app/model/user.rb 中尝试这样的操作:

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

    尽管如此,我们可以通过将代码移入 app/models/dwelling.rb 中的 Dwelling 类来改进代码:

    class Dwelling < ActiveRecord::Base
      # ...
      def roomie?(user)
        roomies.include?(user)
      end
    end
    

    然后您将在视图中使用它:

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

    【讨论】:

    • 这非常有效。我不会说我完全理解第一段中描述的实际问题 - 即我不理解 UsersController 对象是什么 - 但我将尝试阅读它。感谢您解决我的障碍。
    • 在 users_controller.rb 的顶部,您会看到控制器被定义为 class UsersController &lt; ApplicationController。在该类定义中,我们定义了许多方法,例如indexshow 等。这些方法是instance 方法。当 Rails 将请求路由到 UsersController 时,它会创建该类的一个新实例。由于您在 UsersController 类中定义了is_roomie?,因此它是UsersController 实例中的实例方法,而不是User
    【解决方案2】:

    current_user 对象没有方法 is_roomie?。这是您的控制器中的一种方法。您可以在显示操作中调用该方法并使其可用于视图,如下所示:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-05
      • 1970-01-01
      • 2013-12-09
      • 2016-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多