载波不产生方法

carrierwave not creating method

我正在尝试通过载波将图片上传到表单并通过图片标签显示图片。

因此我生成了一个图片上传器和一个迁移

$ rails generate uploader Picture
$ rails generate migration add_picture_to_cpostings picture:string

并迁移。

我也加了

mount_uploader :picture, PictureUploader

到 cpostings 模型。

在控制器中我允许了图片属性

def cposting_params
    params.require(:cposting).permit(:content, :spots, :class_date, :class_time, :title, :picture)
end

上传

  <%= f.file_field :picture, accept: 'image/jpeg,image/gif,image/png' %>

表单有效,但是当我尝试使用

显示帖子中的图片时
<%= image_tag cposting.picture.url if cposting.picture? %>

我收到以下错误:

undefined local variable or method `cposting' for #<#:0x007f9629cc76f0>

根据railstutorial.org,该方法应该由carrierwave自动创建。你知道为什么它在这里不起作用吗?

undefined local variable or method `cposting' for #<#:0x007f9629cc76f0>

从错误消息中可以清楚地看出,您的视图没有找到 cposting 变量。您必须在相应控制器的操作中将此 cposting 变量声明为实例变量 (@cposting),然后它将在您的视图文件中可用,您将不会收到此错误。

更新

变化:

<%= image_tag cposting.picture.url if cposting.picture? %>

收件人:

<%= image_tag @cposting.picture.url if @cposting.picture? %>