【问题标题】:Access attribute with has_many/belongs to具有 has_many/belongs 的访问属性
【发布时间】:2014-04-09 13:57:55
【问题描述】:

我的模型设置是这样的

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:

【问题讨论】:

  • Ruby 更喜欢使用&lt;% @gallery.gallery_images.each do |image| %&gt; 而不是for 循环。诚然,最终结果是一样的。
  • 如果你有时间,那么让我们在聊天chat.stackoverflow.com/rooms/48530/ror进行调试

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


【解决方案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

【讨论】:

  • 感谢 Rich,我选择了更简单的方法,因为初始实现有点 OTT,仍然出现重复错误,但现在认为这更像是 .load() 方法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-03
  • 1970-01-01
相关资源
最近更新 更多