2

我有一个用户模型的嵌套资源图片。如果我尝试使用“remote_file_url”上传图片,它会将图片上传到carrierwave tmp 目录,但不会将它们移动到实际目录。那“应该”是一个验证问题。但事实并非如此。它在控制台中工作得很好:

p = Picture.find(360)
p.remote_file_url = "http://example.com/somepic.jpg"
p.save!

我用图片更新用户的请求的参数:

 "user"=>{"pictures_attributes"=>{"0"=>{"remote_file_url"=>"http://example.com/somepic.jpg", "id"=>"359"}

如果我在没有 remote_file_url 的情况下上传(只是输入文件字段),它可以工作:

 "user"=>{"pictures_attributes"=>{"0"=> { "file"=>#<ActionDispatch::Http>, "remote_file_url"=>"",  "id"=>"359"}

当我使用“remove_file”功能时也会出现同样的问题。在控制台中工作得很好,但不适用于视图/控制器更新。

====================

更新

控制器:

  def update
    @user = current_user
    if @user.update_attributes!(params[:user])
      respond_to do |format|
        format.js { render :json => @user.to_json(:methods => [:pictures]) }
        format.html {redirect_to :back, :notice  => "Successfully updated user."}
      end
    else
      render :action => 'edit'
    end
  end

图片型号:

class Picture < ActiveRecord::Base
  attr_accessible :file, :file_cache, :remove_file, :position, :remote_file_url
  mount_uploader :file, PictureUploader
  belongs_to :user
end

用户模型

# encoding: UTF-8
class User < ActiveRecord::Base
  attr_accessible :remote_file_url, :beta_token, :wants_gender, :gender, :radius, :email, :password, :password_confirmation, :remember_me, :region, :latitude, :longitude, :gmaps, :pictures_attributes
  has_many :pictures, :dependent => :destroy
  accepts_nested_attributes_for :pictures, :allow_destroy => true
end

非常基本的东西......我删除了用户模型的设计定义......

= simple_form_for @user, :url => profile_path(@user) do |f|
  %ul.profiles.users
    - @user.pictures.each_with_index do |picture, i|
      %li.user
      .fields
        = f.simple_fields_for :pictures, picture do |picture_from|
          - if picture.file.present?
            = picture_from.input :_destroy, :as => :boolean
          = picture_from.input :position
          = picture_from.input :file
          = picture_from.input :remote_file_url, :as => :hidden
          = picture_from.input :file_cache
4

2 回答 2

1

这是因为 attr_accessible。如果您将挂载的上传程序的实例变量名称设置为 attr_accessible,Ruby 将为您创建访问器……这将干扰 CarrierWave 的设置器。

不要使任何已安装的上传程序变量名称 attr_accessible。

于 2012-10-01T00:24:00.847 回答
0

我有一个类似的问题,当我设置 remote_image_url 时,图像不会与模型本身一起保存。

问题是设置remote_image_url后图片没有保存。

这是因为我self.taker = 'Andrew'从 User 模型中调用了一个委托方法,该方法会自动将 picture.taker 中的“Andrew”保存到数据库中。我不得不避免这种情况并使用'self.picture.taker ='Andrew'来避免图片被持久化。然后,当我调用 user.save 时,它​​将保存关联的图片并正确创建缩略图。

这种情况是特定的,但重点是在设置 remote_image_url 后检查你的图片对象是否真的被保存了。

于 2012-02-22T09:03:32.733 回答