PagesController中几乎相同的方法在Rails 4中产生未定义的方法错误

时间:2016-03-16 08:09:36

标签: ruby-on-rails

我的Rails 4应用程序中有三个表 - 一个用于游戏类别主题类别主题都有:name列,而游戏包含游戏开始时starts_at等信息

在我的 PagesController 中,我可以使用带有参数值的find_by显示来自游戏主题的数据:< / p>

 topic = Topic.find_by_name(params[:topic])
 @games = Game.for_topic(topic).upcoming.order(:starts_at)

这很好用。

奇怪的是,当我使用相同的推理但使用类别而不是主题时,就像这样:

 category = Category.find_by_name(params[:category])
 @games = Game.for_category(category).upcoming.order(:starts_at)

我收到一条错误消息:

undefined method `for_category'

这让我感到困惑,因为我肯定是在我的for_表达式中定义类别和使用它。我在思考中犯了错误吗?

附加

CreateCategories Migration

 class CreateCategories < ActiveRecord::Migration
  def change
    create_table :categories do |t|
    t.belongs_to :topic, index: true
     t.string :name, :null => false

     t.timestamps
    end
   end
  end

CreateTopics Migration

 class CreateTopics < ActiveRecord::Migration
  def change
    create_table :topics do |t|
       t.string :name, :null => false

       t.timestamps
      end
     end
   end

1 个答案:

答案 0 :(得分:5)

我认为您在for_topic模型中设置了命名范围Game。但缺少for_category,这就是它失败的原因。

尝试在for_category模型中设置命名范围Game