我正在尝试使用paperclip gem上传图片, 刚才,我的模特是:
我的模特
class Advert < ActiveRecord::Base
has_attached_file :image
#accepts_nested_attributes_for :image
end
我的部分观点:
<%= form_for :advert do |f| %>
<p>
<%= f.label :image %><br>
<%= f.file_field :image %>
</p>
<% 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=#<Tempfile:/var/folders/sv/h26bfj7167jgnb1nm_nstw300000gn/T/RackMultipart20140417-540-iychs8>, @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
我必须允许图像并添加模型,我可以做些什么改变?
答案 0 :(得分:2)
首先,您只需在强参数中包含附件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
)将在保存到数据库时自动处理。
其次,您需要为模型中的图像添加验证。自Paperclip 4.0以来,您必须至少验证图像的内容类型,或明确说明您不想这样做。因此,在您的模型中,您需要添加以下内容之一:
如果要验证内容类型,请执行以下操作:
validates_attachment_content_type :image, :content_type => ["image/jpg", "image/jpeg", "image/gif", "image/png"]
如果您只想验证文件名,请执行以下操作:
validates_attachment_file_name :image, :matches => [/jpe?g\z/, /gif\z/, /png\z/]
如果您想要明确地不验证附件的内容,那么:
do_not_validate_attachment_file_type :image
或者,如果您需要检查图像是否存在,特定类型以及不超过某个文件大小,则可以使用validates_attachment
组合验证。有关详细信息,请参阅此处的文档:https://github.com/thoughtbot/paperclip
答案 1 :(得分:-1)
删除image_attributes并将:image添加到permit hash