Ruby on rails未经许可的参数:image
我正在尝试使用paperclip gem上传图像,刚才,我的模型是:
我的模特
class Advert < ActiveRecord::Base has_attached_file :image #accepts_nested_attributes_for :image end
我的部分观点:
我的控制器:
def new logger.info "Processing the request New..." @advert = Advert.new end def create logger.info "Processing the request Create..." #logger.info JSON.parse( params[:advert].to_json ) @advert = Advert.new( advert_params ) @advert.save redirect_to action: "index" end private def advert_params params.require(:advert).permit(:title, :features, :description, :areadescription, :rooms, :bathroom, :price, :type, :source, :originaldate, images_attributes: [:image]) end
请求:
Processing by AdministrationController#create as HTML Parameters: {"utf8"=>"✓", "authenticity_token"=>"VGRNZCT8eo231iT2Fa2Bq2EsG+/4kfkzpgV7NQA4/6o=", "advert"=>{"title"=>"dfas", "features"=>"", "description"=>"", "areadescription"=>"", "rooms"=>"", "bathroom"=>"", "price"=>"", "type"=>"", "source"=>"", "originaldate"=>"", "image"=>#<ActionDispatch::Http::UploadedFile:0x007fb56fc34c78 @tempfile=#, @original_filename="i04.png", @content_type="image/png", @headers="Content-Disposition: form-data; name=\"advert[image]\"; filename=\"i04.png\"\r\nContent-Type: image/png\r\n">}, "commit"=>"Save Advert"} Processing the request Create... Unpermitted parameters: image
我必须允许图像并添加模型,我可以做些什么改变?
首先,您只需要在强参数中包含附加的文件image
:
def advert_params params.require(:advert).permit(:title, :features, :description, :areadescription, :rooms, :bathroom, :price, :type, :source, :originaldate, :image) end
Paperclip使用的四个属性( image_file_name
, image_file_size
, image_content_type
和image_updated_at
)将在保存到数据库时自动处理。
其次,您需要为模型中的图像添加validation。 自Paperclip 4.0以来,您必须至少validation图像的内容类型,或明确说明您不想这样做。 因此,在您的模型中,您需要添加以下内容之一:
如果要validation内容类型,请执行以下操作:
validates_attachment_content_type :image, :content_type => ["image/jpg", "image/jpeg", "image/gif", "image/png"]
如果您只想validation文件名,那么类似于:
validates_attachment_file_name :image, :matches => [/jpe?g\z/, /gif\z/, /png\z/]
如果您想要明确地不validation附件的内容,那么:
do_not_validate_attachment_file_type :image
或者,如果需要检查图像是否存在,特定类型以及不超过某个文件大小,则可以使用validates_attachment
组合validation。 有关详细信息,请参阅此处的文档: https://github.com/thoughtbot/paperclip
: https://github.com/thoughtbot/paperclip
删除image_attributes并将:image添加到permit哈希