以下のようなTag-Service-Categoryが関連しているテーブルにて、
tag/show/html.erbページでServiceのCategory情報を取得したい。
ruby
1class Tag < ActiveRecord::Base 2 has_many :service_tags 3 has_many :services, through: :service_tags 4end
ruby
1 2class ServiceTag < ActiveRecord::Base 3 belongs_to :service 4 belongs_to :tag 5end
ruby
1 2class Service < ActiveRecord::Base 3 has_many :service_tags 4 has_many :tags, through: :service_tags 5 has_many :service_categories 6 has_many :categories, through: :service_categories 7end
ruby
1class ServiceCategory < ActiveRecord::Base 2 belongs_to :service 3 belongs_to :category 4end 5
ruby
1class Category < ActiveRecord::Base 2 has_many :service_categories 3 has_many :services, through: :service_categories 4end
上記状態でviewでServiceをeachで表示しつつ、各ServiceのCategoryを表示したいです。
現在は以下のように取得しておりますが、正常に表示ができておりません。
tag/show.html.erb
ruby
1<% @tag.services.each do |service| %> 2 <% service.categories.each do |category| %> 3 <span class="category" class="<%= category.id %>"><%= category.name %></span> 4 <% end %> 5<% end %> 6
@tag=Tag.find params[:id]