【问题标题】:Trouble rendering images uploaded with CarrierWave无法渲染使用 CarrierWave 上传的图像
【发布时间】:2013-09-18 02:07:50
【问题描述】:

我正在构建一个基本的 Rails 4 应用程序,但似乎遇到了令人沮丧的问题。我一直在关注CarrierWave Railscast,虽然我能够让图像显示在 /image/show.html.erb 上,但我在获取我上传的任何图像以显示时遇到了一些困难在画廊中,每个图像都与之相关联。

奇怪的是,没有记录任何错误。页面加载时页面或终端中没有出现任何 Rails 错误;我知道有问题的唯一方法是图像应该出现的 div 根本不显示。

我真的很难过。如果您看一下,画廊的 show 操作中的 .images div 会呈现,但绝对没有任何子元素呈现。我做错了什么?

Source code here

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 中进行什么更改,无论如何,其中的所有内容似乎都是空白的。我已经尝试多次更改“@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>

【问题讨论】:

  • 你真的在创建图片的时候设置了gallery_id吗?
  • 是的,不过感谢您指出这一点。我已经更新了我的问题以进一步反映这一点。 :)
  • 我们可以看看你的 ImageUploader 吗?
  • 当然,我已经更新了原始问题以包含它。
  • 你在哪里设置galery_id?我找不到它。

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


【解决方案1】:

您需要将图库和图片关联起来。一种选择是像现在一样将 gallery_id 传递给新操作,将其设置在新图像的控制器中,添加一个隐藏字段以将其传输到创建操作并将那里的参数列入白名单。

另一种选择是将图像路由嵌套到图库路由中,如下所示:

resources :galleries do
  resources :images
end

这将创建像 /galleries/123/images/234galleries/1233/images/new 这样的 URL。您可以创建指向这些页面的链接,例如使用 edit_galleries_image_path(@gallery, @image)。同样,您需要在新图像上的images#new 中设置正确的gallery_id,但这应该让form_for 生成创建操作的正确路径,然后您就可以使用gallery_id 参数。这样做rake routes 应该是一个方便的工具。

【讨论】:

  • 在画廊中嵌套图像似乎是要走的路。但是,目前我收到了undefined method 'images_path',所以我的表单部分看起来需要以某种方式进行调整。从好的方面来说,路由看起来好多了!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-29
  • 1970-01-01
  • 2015-05-17
  • 1970-01-01
  • 2014-03-27
  • 1970-01-01
相关资源
最近更新 更多