我的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
答案 0 :(得分:5)
我认为您在for_topic
模型中设置了命名范围Game
。但缺少for_category
,这就是它失败的原因。
尝试在for_category
模型中设置命名范围Game
。