Jac*_*ody 6 json ruby-on-rails carrierwave
我有一个使用Carrierwave的标准图像上传器.我也在使用Postgres.这就是我的迁移在将图像添加为JSON时的样子:
class AddImagesToListings < ActiveRecord::Migration[5.1]
def change
add_column :listings, :images, :json
remove_column :listings, :image
end
end
Run Code Online (Sandbox Code Playgroud)
我想让图像[0]总是有一些图像,但似乎Carrierwave文档只涵盖了单个文件上传的内容.现在,这是我的default_url方法:
def default_url(*args)
ActionController::Base.helpers.asset_path("default/" + ["default.jpg"].compact.join('_'))
end
Run Code Online (Sandbox Code Playgroud)
当我只有:图像时,这是有效的,但现在却没有.有没有办法为images [0]设置默认值,这样我就可以获得每个列表的有效图像[0] .url(无论用户是否在列表中添加图像)?
由于 Carrierwave 在这件事上没有帮助,也许您可以使用诸如为这项工作编写助手或回调之类的东西。以下是一些您可能会喜欢的建议。
Run Code Online (Sandbox Code Playgroud)module CarrierwaveHelper def render_image_url(images, index) return "Default.jpg" if index == 0 images[index].url end end
只需在视图中调用 render_image_url(images,0) 而不是 images[0].url
before_create :assign_default_image 或者您可能需要 before_update
def assign_default_image
self.image[0] = "default.jpg"
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
221 次 |
| 最近记录: |