显示按其FK ID分组的图像

时间:2014-04-24 13:03:05

标签: ruby-on-rails ruby group-by

到目前为止,我使用Rails 4进行了以下设置

class Tournament < ActiveRecord::Base
  has_many :fixtures
  has_one :gallery
  has_many :gallery_images, :through => :gallery
end

class Gallery < ActiveRecord::Base
  belongs_to :tournament
  has_many :gallery_images, dependent: :destroy
  accepts_nested_attributes_for :gallery_images, allow_destroy: :true
end

class GalleryImage < ActiveRecord::Base
  belongs_to :gallery
end

我的数据库设置如此

 create_table "galleries", force: true do |t|
   t.integer  "tournament_id"
   t.datetime "created_at"
   t.datetime "updated_at"
 end

 create_table "gallery_images", force: true do |t|
   t.datetime "created_at"
   t.datetime "updated_at"
   t.string   "photo_file_name"
   t.string   "photo_content_type"
   t.integer  "photo_file_size"
   t.datetime "photo_updated_at"
   t.integer  "gallery_id"
 end

 create_table "tournaments", force: true do |t|
   t.string   "name"
   t.date     "tourn_date"
   t.string   "tourn_location"
   t.datetime "created_at"
   t.datetime "updated_at"
end

我想把一个画廊及其所有图像放到一个对象中,以便我可以遍历每个锦标赛的所有gallery_images

<div id="verticalTab">
  <ul class="resp-tabs-list">
    <% @tournaments.each do |t| %>
      <li><%= t.name %></li>
    <% end %>
  </ul>
  <div class="resp-tabs-container">
  <div>    
  <% @tournaments.each do |t| %>
  <div class="clear"></div>
    <% g.gallery_images.each do |i| %>
      <ul class="team-gallery"> 
          <li><%= image_tag(i.photo.url(:gallery_image)) %></li>
        <% end %>  
      </ul>
    <% end %>

控制器

 def index
   @tournaments = Tournament.all
 end

我有点不确定如何按比赛分组gallery_images

赞赏任何指针

1 个答案:

答案 0 :(得分:1)

为你的锦标赛模特尝试类似的东西

class Tournament < ActiveRecord::Base
  has_many :fixtures
  has_one :gallery
  has_many :gallery_images, through: :gallery
end

然后在您的视图中,您可以执行类似

的操作
  <ul class="resp-tabs-list">
    <% @tournaments.each do |t| %>
      <li><%= t.name %></li>
      <% t.gallery_images.each do |img| %>
      <% end %>
    <% end %>
  </ul>

或者你也可以像roman.brodetski那样做一些不需要你修改模型的东西

  <ul class="resp-tabs-list">
    <% @tournaments.each do |t| %>
      <li><%= t.name %></li>
      <% t.gallery.gallery_images.each do |img| %>
      <% end %>
    <% end %>
  </ul>

(请注意,您的控制器变量名称@tournaments与您在视图中引用的名称不一致,因此结果为零)

另外需要注意的是,你的模特锦标赛和画廊是一对一的,我认为你可能想要的是你的问题是锦标赛和画廊是一对多的关系,在这种情况下你的锦标赛模型应该看起来像

class Tournament < ActiveRecord::Base
  has_many :fixtures
  has_many :galleries
end  

在这种情况下,您可以让您的视图执行类似

的操作
  <ul class="resp-tabs-list">
    <% @tournaments.each do |t| %>
      <li><%= t.name %></li>
      <% t.galleries.map{|a| a.gallery_images}.flatten.each do |img| %>
      <% end %>
    <% end %>
  </ul>
相关问题