简体   繁体   English

使用回形针更新Ruby on Rails上的头像

[英]Updating avatar on Ruby on Rails with paperclip

I've looked around and I cannot figure out why this is working. 我环顾四周,无法弄清楚为什么这样做。 I allow users to sign up, without needing them to upload avatars at first. 我允许用户注册,而不需要他们首先上传头像。 However, if they wish, they can upload avatars after signing up. 但是,如果他们愿意,他们可以在注册后上传头像。 I allow them to edit their avatar in a "profiles" controller, not in the user controller. 我允许他们在“配置文件”控制器中编辑他们的头像,而不是在用户控制器中。 However, the avatar won't update. 但是,头像不会更新。 I'm using devise for the users. 我正在为用户使用设计。 Code below 代码如下

<%= form_for edit_user_path(current_user.id), :html => { :multipart => true } do |form| %>
  <%= form.file_field :avatar %>
  <%= form.submit "upload" %>
<% end %>

And in the Users controller, I have this: 在Users控制器中,我有这个:

def edit
  @user = User.find(params[:id])
  @user.update_attribute(:avatar, params[:user][:avatar])
end

And in the user model, I have this 在用户模型中,我有这个

has_attached_file :avatar, :styles => { :show => "150x150#" }, :default_url => 'missing_:style.png'

The avatar does not update or save. 头像不会更新或保存。 I'm not sure why. 我不知道为什么。

Update with new form code: 使用新的表单代码更新:

<%= form_for current_user, :url => {:action => 'update'}, :html => { :multipart => true } do |form| %>
  <%= form.file_field :avatar %>
  <%= form.submit "upload" %>
<% end %>

In the profiles controller, I have this: 在配置文件控制器中,我有这个:

def update
  @user = User.find(params[:id])
  @user.update_attribute(:avatar, params[:user][:avatar])
end

I get this error: undefined method `name' for # 我收到此错误:未定义的方法`name'为#

Parameters being passed on the request are below 在请求上传递的参数如下

{"utf8"=>"✓",
 "_method"=>"put",
 "authenticity_token"=>"cxANtlyj+W+ykSnivfQTfTznkpt7yXe75E8jWI1IC+o=",
 "user"=>{"avatar"=>#<ActionDispatch::Http::UploadedFile:0x000001032ac7c8         @original_filename="pictester.png",
 @content_type="image/png",
 @headers="Content-Disposition: form-data; name=\"user[avatar]\";     filename=\"pictester.png\"\r\nContent-Type: image/png\r\n",
 @tempfile=#<File:/var/folders/x9/gvnnn6s9585gkxw40c51d3540000gn/T/RackMultipart20130622-    10366-a8ome3>>},
 "commit"=>"upload",
 "id"=>"1"}

Updating attributes is done inside def update , not def edit . 更新属性是在def update完成的,而不是def edit This is for rendering the form. 这是为了呈现表单。

In profiles_controller.rb profiles_controller.rb

def update
    @user = User.find(params[:id])
    @user.update_attribute(:avatar, params[:user][:avatar])
end

should work. 应该管用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM