has_many /属于的访问属性

时间:2014-04-09 13:57:55

标签: ruby-on-rails ruby ruby-on-rails-4 associations

我的模型设置如此

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

要在我的show动作中访问我的图库图像(因为有多个图像)我正在这样做

<% 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个?

enter image description here

1 个答案:

答案 0 :(得分:1)

从我们的讨论中,这是它应该如何运作:

#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