我想在tag / show.html.erb中获取下面的多对多关系表(Tag-Service-Category)中的数据。
class Tag < ActiveRecord::Base
has_many :service_tags
has_many :services, through: :service_tags
end
class ServiceTag < ActiveRecord::Base
belongs_to :service
belongs_to :tag
end
class Service < ActiveRecord::Base
has_many :service_tags
has_many :tags, through: :service_tags
has_many :service_categories
has_many :categories, through: :service_categories
end
class ServiceCategory < ActiveRecord::Base
belongs_to :service
belongs_to :category
end
class Category < ActiveRecord::Base
has_many :service_categories
has_many :services, through: :service_categories
end
我写了这样的代码,但它没有用。 @tag = Tag.find(params [:id])
<% @tag.services.each do |service| %>
<% service.categories.each do |category| %>
<span class="category" class="<%= category.id %>"><%= category.name %></span>
<% end %>
<% end %>
控制器/ tags_controller.rb
class TagsController < ApplicationController
def show
@tag = Tag.find(params[:id])
@tags = Tag.all
end
end
答案 0 :(得分:0)
虽然您的数据库关系正确,但您仍然需要调用连接模型。因为您要做多对多的关系,所以您需要创建一个中间数组。尝试将此添加到您的视图中:
<% services_array = [] %>
<% @tag.service_tags each do |service_tag| %>
<% services_array << service_tag.service %>
<% end %>
<% services_array.each do |service| %>
<span class="category">
<%= service.service_category.category.id %>
<%= service.service_category.category.name %>
</span>
<% end %>