具有has_many /属于的访问属性

问题描述 投票:0回答:1

我有这样的模型设置

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

class GalleryImage < ActiveRecord::Base
  belongs_to :gallery
  belongs_to :gallery_category
end


class GalleryCategory < ActiveRecord::Base
  has_many :gallery_images
end

要在我的显示操作中访问我的画廊图像(因为有多个图像,我正在执行此操作

<% for image in @gallery.gallery_images %>
  <li><%= image_tag(image.photo.url(:gallery_flexslider)) %>
    <p class="flex-caption"></p>  
  </li>
<% end %>

将显示每个图像,但是对于每个图像,我想在我的图像中添加相应的图库类别

<p class="flex-caption"></p>

我似乎无法弄清楚如何获取gallery_category以匹配gallery_image的实例。

我已经尝试过

 <% @gallery.gallery_images.each do |image| %>
  <li><%= image_tag(image.photo.url(:gallery_flexslider)) %>
    <p class="flex-caption"><%= image.gallery_category.name %></p>  
  </li>
<% end %>

但是与分配给图像的正确图库类别不符。

我也尝试过:

<% @gallery.gallery_images.each do |image| %>
          <li>
            <%= image_tag(image.photo.url(:gallery_flexslider)) %>
              <% image.gallery_categories.each do |c| %>
                <p class="flex-caption"><%= c.name %></p> 
              <% end %> 
            </li>
        <% end %>

但是会导致错误。

编辑

因此,似乎逻辑在起作用,但我的图像正在复制,在此示例中,实际上仅上传了两张图像,但我正在渲染4:

“在此处输入图像描述”“ >>

我有这样的模型设置,如Gallery Gallery

根据我们的讨论,这是应该如何工作的:

#app/models/image.rb
Class Image < ActiveRecord::Base
    has_many :gallery_images
    has_many :galleries, through: :gallery_images
    has_one  :category, through: :gallery_images #-> I think
end

#app/models/gallery.rb
Class Gallery < ActiveRecord::Base
    has_many :gallery_images
    has_many :images, through: :gallery_images
end

#app/models/gallery_category.rb
Class GalleryImage < ActiveRecord::Base
   belongs_to :gallery
   belongs_to :image
   belongs_to :category
end

#app/models/gallery_category.rb
Class GalleryCategory < ActiveRecord::Base
   belongs_to :gallery
   has_many :gallery_images
end

架构:

images
id | image_info | created_at | updated_at 

galleries
id | name | created_at | updated_at

gallery_images
image_id | gallery_id | category_id

gallery_categories
id | gallery_id | name | created_at | updated_at

这可能开箱即用


[如果您正在寻找简单的东西,还应该考虑在type中添加GalleryImages属性-

gallery_images
id | gallery_id | image_id | type | created_at | updated_at
ruby-on-rails ruby ruby-on-rails-4 associations
1个回答
1
投票

根据我们的讨论,这是应该如何工作的:

© www.soinside.com 2019 - 2024. All rights reserved.