参数缺失或值为空:图库

param is missing or the value is empty: gallery

问题出在 rails 中的 "strong parameters"。 我用蜻蜓上传图片。

问题是,如果我发送一个空表单,我不会得到任何用于错误处理的参数。可能是什么原因?

控制器:

还有一种方法"Create"将图像保存在数据库中,然后将用户发送到包含图片的页面。

def index
  @gallery = Gallery.new
  @galleries = Gallery.all
end

def create
  @gallery = Gallery.new(gallery_params)

  if @gallery.save
    redirect_to galleries_path, flash: { success: 'Your Image was successfully save.' }
  else
    redirect_to :back,          flash: { alert: "Your Image don't save." }
  end
end

def gallery_params
  params.require(:gallery).permit(:image)
end

观看次数:

= form_for @gallery do |f|
  = f.file_field :image
  = f.submit 'Submit', class: 'btn bth-primary btn-lg'

参数:

{"utf8"=>"✓",    "authenticity_token"=>"8eotQtkj8SElqJLdHuOX8r+dWrCJRWTmVcyfd1mSLD/8MjWw/ElH/HCxZFSJ6oOWaxpbLbn4kAg5nlFycsgjHg==", "commit"=>"Submit"}

这是预期的行为,请参阅 ActionController::Parameters#require

的文档

在这些情况下,我通常做的是捕获异常并显示一条快速消息来通知用户。您也可以手动向模型添加错误。

def create
  @gallery = Gallery.new(gallery_params)

  if @gallery.save
    redirect_to galleries_path, flash: { success: 'Your Image was successfully save.' }
  else
    redirect_to :back, flash: { alert: "Your Image don't save." }
  end
rescue ActionController::ParameterMissing => e
  redirect_to :back, flash: { alert: "Please attach an image." }
end