Paperclip:ActionController :: ParameterMissing属性为空时

时间:2014-08-15 03:02:32

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

我正在使用paperclip gem进行图片上传,但是当我的:photo atrribute不存在时,我无法显示错误消息。

我的模型是Image.rb:

validates_attachment :photo, :presence => true,
  :content_type => { :content_type => ["image/jpeg", "image/png"], :message => "must be a jpeg or png" },
  :size => { :in => 0..1.megabytes, :message => "must be less than 1 MB" }

我的控制器创建动作:

  def create
    @images = Image.all
    @image = Image.new(image_params)

    if @image.save
      redirect_to new_image_url, notice: 'Image uploaded.'
    else
      @image.errors.delete(:photo)
      render :new
    end
  end

当我在没有附加图片的情况下提交表单时,它会引发异常并显示页面:

ActionController::ParameterMissing in ImagesController#create
param is missing or the value is empty: image

    def image_params
      params.require(:image).permit(:photo)
    end

除了它之外,它会将错误消息传递给错误哈希,就像其余的一样,因此只会向full_messages显示错误。但它并没有这样做。

知道我做错了吗?

更新:添加要上传的表单

<%= simple_form_for @image, html: { multipart: true } do |f| %>
  <% if @image.errors.any? %>
    <div class="panel panel-default border-danger">
      <div class="panel-heading background-color-danger"><%= pluralize(@image.errors.count, "error") %>:</div>
      <div class="panel-body">
        <ul class="list-unstyled">
        <% @image.errors.full_messages.each do |message| %>
          <li><%= message %></li>
        <% end %>
        </ul>
      </div>
    </div>
  <% end %>

    <div class="form-group">
        <%= f.file_field :photo, error: false, input_html: { class: "form-control" } %>
    </div>

  <hr />

  <div class="form-group">
    <%= f.button :submit, "Upload", class: "btn btn-default" %>
  </div>

<% end %>

**我意识到error: false看起来并不好,但它只是禁用了simple_form内联错误。这不是问题所在。

更新的解决方案:

根据接受的答案,这是我的新创建动作和强大的参数,我已经用它来形成解决这个问题的可行方案。

ImagesController.rb #create

  # POST /images
  def create
    @images = Image.all
    @image = Image.new(image_params)

    if params[:image]
      if @image.save
        redirect_to new_image_path, notice: 'Photo uploaded.'
      else
        @image.errors.delete(:photo)
        render :new
      end
    else
      redirect_to new_image_path, alert: 'Photo cannot be blank.'
    end
  end

强对手

def image_params
  params.require(:image).permit(:photo) if params[:image]
end

2 个答案:

答案 0 :(得分:4)

here起,这应该有效:

def image_params
  params.require(:image).permit(:photo) if params[:image]
end

答案 1 :(得分:0)

好的,我觉得我找到了可以帮到你的东西;看看THIS

我也在我的应用中使用Paperclip gem。如果未附加:image:photo,则会收到错误消息&#34;图片无法显示空白&#34;。

我所做的就是:

图片型号:

has_attached_file :photo
validates_attachment :photo, content_type: { content_type: ["image/jpg", "image/jpeg", "image/png", "image/gif"] }
validates :photo, presence: true 
相关问题