【问题标题】:what could cause a rails scope to throw a NoMethodError什么可能导致 Rails 范围抛出 NoMethodError
【发布时间】:2012-05-10 05:29:08
【问题描述】:

在使用范围时,什么可能导致 Rails 应用程序出现无方法错误?

我有一个包含猫和狗的基本用户类。我需要组合查询并按创建日期对它们进行排序。最终,单个查询将更加复杂。

    class User < ActiveRecord::Base
        has_many :dogs
        has_many :cats

       scope :pets, joins(:dogs).joins(:cats).order("created_at desc")

在视图中

    <%= render @user.pets%>

导致无方法错误

    undefined method `pets' for #<User:0x00000106370cb0>

【问题讨论】:

    标签: mysql ruby-on-rails-3 activerecord scope


    【解决方案1】:

    范围仅在 ActiveRecord 模型上定义类方法。调用它的正确方法是直接在 User 模型上。 User.pets 而不是用户 @user.pets 的实例。

    你可以做的是创建一个在用户实例上调用的方法。

       def pets
         User.joins(:dogs).joins(:cats).order("created_at desc")
       end
    

    因此,@user.pets 是允许的。

    【讨论】:

      猜你喜欢
      • 2011-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-26
      相关资源
      最近更新 更多