我'm building a basic Rails 4 application, and seem to have hit a frustrating snag. I'已经关注CarrierWave Railscast,而我'm able to get images to show up on /image/show.html.erb, I'已经遇到了一些困难,我已经上传到图库中显示的任何图像与每个图像相关联 .
奇怪的是,没有记录任何错误 . 页面或终端中没有任何Rails错误加载页面;我知道一些错误的唯一方法是图像应该出现的div根本不显示 .
我真的很难过这个 . 如果你看,画廊的show动作中的.images div渲染,但绝对没有任何子元素渲染 . 我究竟做错了什么?
app/models/image.rb
class Image < ActiveRecord::Base
belongs_to :gallery
mount_uploader :image, ImageUploader
end
app/models/gallery.rb
class Gallery < ActiveRecord::Base
has_many :images
end
app/uploaders/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
apps/views/images/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 image in @gallery.images"位,但无济于事 .
<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>
1 回答
您需要关联图库和图像 . 一种选择是像现在一样将gallery_id传递给新操作,在新图像的控制器中设置它,添加隐藏字段以将其传输到创建操作并将参数列入白名单 .
另一种选择是将图像路径嵌套到图库路线中,如下所示:
这将创建像
/galleries/123/images/234
和galleries/1233/images/new
这样的URL . 您可以使用edit_galleries_image_path(@gallery, @image)
创建指向这些页面的链接 . 同样,您需要在新图像上的images#new
中设置正确的gallery_id
,但这应该让form_for
生成创建操作的正确路径,然后您可以使用gallery_id
参数 . 走这条路rake routes
应该作为一个方便的工具 .