Search code examples
ruby-on-railsruby-on-rails-3ruby-on-rails-3.1has-many-through

How do i access attributes in has_many :through relationship?


How do i access store name here?@deal instance can access perfectly item name,but when i try to access store name it gives me

no method error 'stores'

How do i get store instance to access store name?Here is the code.Thank you in advance

controller

def show
   unless session[:city_id].nil? || session[:city_id].blank?
   @city = City.find(session[:city_id])
   @[email protected]
   @[email protected]
end

view/show

<% @deal.each do |deal| %>
<%=deal.item_name %>
<%end%>

<%[email protected]_name %>

models

class Store < ActiveRecord::Base
    has_many :deals ,:through =>:store_deals
    has_many :store_deals
end

class Deal < ActiveRecord::Base
    has_many :stores ,:through =>:store_deals
    has_many :store_deals
end

class StoreDeal < ActiveRecord::Base
    belongs_to :store
    belongs_to :deal
end

Solution

  • @deal is most likely an array of deals. @city.deals implies you could have multiple deals per city. This wil cause a problem when you try to do

    @[email protected]
    @[email protected]
    

    try something like:

    @deals = @city.deals
    @stores = @deals.collect(&:stores)