سؤال

I have my models setup like so

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

To access my gallery images within my show action (as there are multiple images) I am doing this

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

Which will display each image, but for each of those images I want to add the corresponding gallery Category within my

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

I can't seem to figure out how to get the gallery_category to match the instance of the gallery_image.

I have tried

 <% @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 %>

but that doesn't correspond to the correct gallery category that is assigned to the image.

I have also tried:

<% @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 %>

but that results in an error.

Edit

So it seems the logic in place is working but my images are being duplicated, in this example there are actually only two images uploaded but I am rendering 4:

enter image description here

هل كانت مفيدة؟

المحلول

From our discussion, this is how it should work:

#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

Schemas:

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

This might not work out of the box


If you're looking for something simple, you should also consider just adding a type attribute to your GalleryImages -

gallery_images
id | gallery_id | image_id | type | created_at | updated_at
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top