我想在我的rails应用程序中使用paperclip为用户添加图片
我的表单如下:
<%= form_tag :controler => "users", :action => :uploadimage, :class => "form-horizontal", html: { multipart: true }, :method => :post do |f| %>
<input type="hidden" id="user" name="userid" value="<%= @user.id %>" />
<div class="form-group">
<div class="col-sm-3"></div>
<div class="col-sm-9">
<input type="file" name="upload[image]" required="true" class="form-control"/>
</div>
</div>
<div class="form-group">
<div class="col-sm-3"></div>
<div class="col-sm-9">
<input type="submit" class="btn btn-default">
<%#= f.submit t("main.save"), :icon => :save, :onclick => "validate(); return false;" %>
</div>
</div>
<% end %>
上传操作如下所示:
def uploadimage
if request.post?
@user = User.find(params[:userid])
if @user.update_attribute(:image, params[:image])
flash[:notice] = t("flash.saved")
redirect_to :action => :settings
end
end
end
它完成得很好,但是在数据库中它没有添加任何东西,而且在文件存储中也没有。
用户模型有:
has_attached_file :image, styles: { small: "64x64", med: "100x100", large: "200x200" },
:path => ":rails_root/public/uploads/:id/:filename",
:url => "/uploads/:id/:filename"
validates_attachment :image, :content_type => { :content_type => "image/jpg" }
正确完成数据库迁移,在用户表中设置了所有需要的字段。
可能是什么问题?
答案 0 :(得分:1)
问题是params[:image]
应为params[:upload][:image]
,因为表单中输入字段的name
为upload[image]
def uploadimage
if request.post?
@user = User.find(params[:userid])
if @user.update_attribute(:image, params[:upload][:image])
flash[:notice] = t("flash.saved")
redirect_to :action => :settings
end
end
end