我正在构建一个基本的Rails 4应用程序,似乎遇到了令人沮丧的障碍。我一直在关注CarrierWave Railscast,虽然我能够将图像显示在/image/show.html.erb上,但我在获取上传的任何图片方面遇到了一些困难在图库中显示每个图像与之关联。
奇怪的是,没有记录任何错误。页面或终端中没有任何Rails错误加载页面;我知道错误的唯一方法是图像应该出现的div根本不显示。
我真的很难过。如果你看,画廊的show动作中的.images div渲染,但绝对没有任何子元素渲染。我做错了什么?
app / models / image.rb
class Image < ActiveRecord::Base
belongs_to :gallery
mount_uploader :image, ImageUploader
end
应用/模型/ gallery.rb
class Gallery < ActiveRecord::Base
has_many :images
end
应用/上传/ image_uploader.rb
class ImageUploader < CarrierWave::Uploader::Base
include CarrierWave::RMagick
storage :file
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
version :thumb do
process :resize_to_limit => [200, 200]
end
end
应用/视图/图像/ show.html.erb
下面,我们可以看到图像可以毫无问题地呈现,因为这是他们各自控制器的视图。
<p>
<strong>Title:</strong>
<%= @image.title %>
</p>
<p>
<strong>Description:</strong>
<%= @image.description %>
</p>
<p>
<strong>Image:</strong>
<%= image_tag @image.image_url.to_s %>
</p>
/apps/views/galleries/show.html.erb
这是一切都变得棘手的地方。首先,无论我在图像div中改变什么,它内部的一切似乎都是空白的。我曾尝试多次更改“for gallery.images”中的“for image”,但无济于事。
<div id="images">
<% for image in @gallery.images %>
<div class="image">
<%= image_tag image.image_url(:thumb) %>
<%= image.description %>
<div class="name"><%= image.title %></div>
<div class="actions">
<%= link_to "edit", edit_image_path(image) %> |
<%= link_to "remove", image, :confirm => 'Are you sure?', :method => :delete %>
</div>
</div>
<% end %>
<div class="clear"></div>
</div>
<p>
<%= link_to "Add a Painting", new_image_path(:gallery_id => @gallery) %> |
<%= link_to "Remove Gallery", @gallery, :confirm => 'Are you sure?', :method => :delete %> |
<%= link_to "View Galleries", galleries_path %>
</p>
答案 0 :(得分:1)
您需要关联图库和图像。一种选择是像现在一样将gallery_id传递给新操作,在新图像的控制器中设置它,添加隐藏字段以将其传输到创建操作并将参数列入白名单。
另一种选择是将图像路线嵌套到图库路线中,如下所示:
resources :galleries do
resources :images
end
这会创建/galleries/123/images/234
和galleries/1233/images/new
等网址。您可以使用edit_galleries_image_path(@gallery, @image)
创建指向这些页面的链接。同样,您需要在新图片上的gallery_id
中设置正确的images#new
,然后让form_for
生成创建操作的正确路径,然后您拥有gallery_id
参数可用。走这条路rake routes
应该是一个方便的工具。