katie
katie

Reputation: 2951

How do i access names of one model from relationship of three models?

I need to print out in the index view, all items from a certain city under category with id 2(any number).So far i have instance of all items in the city(as shown below),now i want to filter them by category.How do i do that?This is my code below

    class CategoryController < ApplicationController
    def index
    @city= City.find(session[:city_id])
    @[email protected]
    end
    end

index view

     <%[email protected] do |item|%>
     <%=item.item_name%>
     <%end%>

Models

       class City < ActiveRecord::Base
       has_many :items 
       end

       class Item < ActiveRecord::Base
   belongs_to :city
   belongs_to :category
       end

       class Category < ActiveRecord::Base
       has_many :items
       end 

Upvotes: 1

Views: 48

Answers (1)

damienbrz
damienbrz

Reputation: 1806

Controller: You should be able to do something like:

@items = Item.find_by_city_and_category("city", "category")

Or something like:

@items = Item.where(:category => "category", :city => "city")

View:

@items.each do |item|
 item.name

Upvotes: 1

Related Questions