我想从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 [:编号])
<% @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
您可以添加控制器吗? –
谢谢你的帮助!是的。 – Dan
你的意思是它不工作?有没有错误,或只是没有显示出来? –