Rails - 在教程索引视图中显示教程所属的类别

时间:2013-04-20 05:14:44

标签: ruby-on-rails ruby has-many belongs-to

我有tutorial模型和tutorial_category模型。我已使用has_many belongs_to关系将两者联系在一起。在我的教程索引视图中,我正在循环学习这样的教程:<% @tutorials.each do |tutorial| %>。在该循环中,我想显示每个教程所属的类别。我正在尝试像<%= tutorial.tutorial_categories.title %>那样(标题是tutorial_category模型中的attr,我也有:tutorial_id作为tutorial_category模型中的属性。并且:tutorial_category_id是教程模型中的attr,就此而言)。

以下是我的教程控制器中的索引操作:

def index
   @tutorials = Tutorial.all
   @tutorial = Tutorial.new
   @tutorial_categories = TutorialCategory.select("DISTINCT title, id")

   respond_to do |format|
      format.html # index.html.erb
      format.json { render :json => @tutorials }
  end
end

我无法弄清楚我在这里做错了什么。根据我的经验,这应该都能正常工作,虽然距离我编写任何Ruby代码已经有几个月了,所以我可能在这里错过了一些愚蠢的东西。任何帮助将不胜感激!

更新:我的模特

class Tutorial < ActiveRecord::Base
  attr_accessible :content, :title, :tutorial_category_id
  belongs_to :tutorial_category
end

class TutorialCategory < ActiveRecord::Base
  attr_accessible :title, :tutorial_id
  has_many :tutorials
end

1 个答案:

答案 0 :(得分:0)

如果您希望能够列出教程旁边的教程类别,请执行以下操作:

def index
   @tutorials = Tutorial.includes(:tutorial_category)
   @tutorial = Tutorial.new
   ...
  end
end

然后你可以迭代它们

<% @tutorials.each do |tutorial| %>
  <%= tutorial.tutorial_category.title %>
<% end %>