ruby - Rails - Show which category a tutorial belongs to in the tutorial index view -
i have tutorial
model , tutorial_category
model. have linked 2 using has_many
belongs_to
relationship. in tutorials index view, looping through tutorials so: <% @tutorials.each |tutorial| %>
. inside loop, wanting display category each tutorial belongs to. i'm trying <%= tutorial.tutorial_categories.title %>
(title attr in tutorial_category model , have :tutorial_id attribute in tutorial_category model. , :tutorial_category_id attr in tutorial model, matter).
here index action in tutorials controller:
def index @tutorials = tutorial.all @tutorial = tutorial.new @tutorial_categories = tutorialcategory.select("distinct title, id") respond_to |format| format.html # index.html.erb format.json { render :json => @tutorials } end end
i can't figure out i'm doing wrong here. experience, should work correctly, although it's been few months since i've written ruby code i'm missing stupid here. appreciated!
update: models
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
if want able list tutorial categories next tutorials following:
def index @tutorials = tutorial.includes(:tutorial_category) @tutorial = tutorial.new ... end end
then can iterate on them
<% @tutorials.each |tutorial| %> <%= tutorial.tutorial_category.title %> <% end %>
Comments
Post a Comment