【发布时间】: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 更喜欢使用
<% @gallery.gallery_images.each do |image| %>而不是for循环。诚然,最终结果是一样的。 -
如果你有时间,那么让我们在聊天chat.stackoverflow.com/rooms/48530/ror进行调试
标签: ruby-on-rails ruby ruby-on-rails-4 associations