我正在尝试创建一个画廊页面,链接到相册。相册工作正常,但我正在尝试将每个gallery_id中的第一张图像拉到画廊页面。我有一个画廊有许多照片,照片属于画廊。我得到的是为每个相册加载的第一张图像。
类GalleriesController < ApplicationController
def index
@gallery = Gallery.paginate(page: params[:page]).per_page(6)
@photos = Photo.find(:all, :limit => 1)
enddef show @gallery =Gallery.find(参数:id) @photos= @gallery.photos.all end end
galleries/index.html。
<% provide(:title, 'Photo Galleries') %>.
<div id="galleries">
<%= will_paginate @gallery %>
<ul class="thumbnails">
<% @gallery.each do |gallery| %>
<li class="span4">
<div class="thumbnail">
<% @photos.each do |photo| %>
<%= link_to image_tag(photo.image), gallery_path(gallery)%>
<% end %>
<h4><%= gallery.name %></h4>
</div>
</li>
<% end %>
</ul>
</div>路线
resources :galleries, :has_many => :photos任何帮助都将不胜感激。
发布于 2013-01-10 10:05:36
我很确定这就是你想要的:
class GalleriesController < ApplicationController
def index
@gallery = Gallery.paginate(page: params[:page]).per_page(6)
end
end_
# galleries/index.html
<% provide(:title, 'Photo Galleries') %>
<div id="galleries">
<%= will_paginate @gallery %>
<ul class="thumbnails">
<% @gallery.each do |gallery| %>
<li class="span4">
<div class="thumbnail">
<%= link_to image_tag(gallery.photos.first.image), gallery_path(gallery) %>
<h4><%= gallery.name %></h4>
</div>
</li>
<% end %>
</ul>
</div>您的问题是,在索引操作中,您抓取了所有图像,而不管它们属于哪个图库,然后在视图中遍历所有图像并显示它们。
由于您的关联(图库has_many照片),您可以使用gallery.photos访问图库的照片。
在我的示例中,我显示了每个图库的第一个图像:gallery.photos.first
如果你想从有问题的图库中随机选择一张图片,你可以使用sample。即gallery.photos.sample
发布于 2013-01-07 04:03:38
您必须使用关系,这是您在这里所需要的。我尝试修复代码并添加注释。
class GalleriesController < ApplicationController
def index
@gallery = Gallery.paginate(page: params[:page]).per_page(6)
# You don't need the photos. You have to access them through gallery,
# or you will get always all photos independent of the gallery.
#@photos = Photo.find(:all, :limit => 1)
end这就是您要查找的视图
# galleries/index.html.erb
<% provide(:title, 'Photo Galleries') %>.
<div id="galleries">
<%= will_paginate @gallery %>
<ul class="thumbnails">
<% @gallery.each do |gallery| %>
<li class="span4">
<div class="thumbnail">
<% gallery.photos.each do |photo| %>
<%= link_to image_tag(photo.image), gallery_path(gallery)%>
<% end %>
<h4><%= gallery.name %></h4>
</div>
</li>
<% end %>
</ul>
</div>如果您只想显示每个图库的第一张图片,则必须以这种方式更改视图:
# galleries/index.html.erb
<% provide(:title, 'Photo Galleries') %>.
<div id="galleries">
<%= will_paginate @gallery %>
<ul class="thumbnails">
<% @gallery.each do |gallery| %>
<li class="span4">
<div class="thumbnail">
<%= link_to image_tag(gallery.photos.first.image), gallery_path(gallery)%>
<h4><%= gallery.name %></h4>
</div>
</li>
<% end %>
</ul>
</div>https://stackoverflow.com/questions/14168828
复制相似问题