新手问题 carrierwave 使用求解

jialezhang · July 31, 2012 · Last by liker replied at October 31, 2013 · 4240 hits

1.rails new nana 2.cd nana=>rails g scaffold post name:string content:text 3.在 Gemfile 里面添加了 gem 'carrierwave' gem 'rmagick' gem 'mime-types' ====>bundle install 4.rails g uploader image 5.修改 image_uplodaer.rb class AttachmentUploader < CarrierWave::Uploader::Base include CarrierWave::RMagick include CarrierWave::MimeTypes

storage :file

def store_dir "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}" end

process :set_content_type

version :thumb, :if => :image? do process :resize_to_fit => [50, 50] end

.....................

protected

def image?(new_file) new_file.content_type.include? 'image' end

end==============>抱歉暂时不会用区块 6.rails g model attach image:string content_type:string 7.attach.rb ==> mount_uploader :image, ImageUploader belongs_to :post 8.post.rb==> has_many :attach 9.views/posts/_form.html.erb==> <%= f.file.field :attach%> 10.修改下其他的东西,去创建时,报错 ActiveModel::MassAssignmentSecurity::Error in PostsController#create Can't mass-assign protected attributes: attach 不解,我都声明了 belongs_to&&has_many 怎么还是传不了啊

多行代码

ruby 代码 代码 `

Can't mass-assign protected attributes: attach 这个是说你的 attach 没有加到 attr_accessible 里

#1 楼 @Rei 哇靠,晚上看着这头像吓人,换个换个

#1 楼 @Rei 谢啦,有木有关于,其他的解决?

#2 楼 @ywencn 写错了,是Can't mass-assign protected attributes: image,image 是 attach 里面的一个属性,但是我已经建立了表间关联了,应该是可以访问子类的属性的吧?如果加到 post 的 attri_accessible 里面的话,报错unknown attribute: image

#3 楼 @ywencn 多美的哥特妹子

#4 楼 @jialezhang

顶楼代码至少有 4 个问题

  1. image_uplodaer.rb 里面的类名叫 AttachmentUploader,命名不符合约定,会导致找不到类(后面又用 ImageUploader)
  2. has_many 应该用复数 has_many :attachs
  3. Post 里面需要 attr_accessor :attachs
  4. 表单里面 f.file.field 应该是 f.file_field

即使上面的问题都纠正,也还是传不了的。因为 attach 不能接受一个文件参数,该接受文件的是 attach.image。

建议你先练习写一个表单创建 attach,然后看这个 api

http://apidock.com/rails/ActionView/Helpers/FormHelper/fields_for

最后你可以考虑写写 js,动态添加多个 attach,或者用 jQuery-File-Upload 这样的插件。

#6 楼 @Rei 1.先弱弱的问下,我把前面的修改完毕了,然后那个该接受参数的是attach.image,,我在 post 和 attach 之间建立了表的连接 (如果那样写has_many.belongs_to没有问题的话),那我该怎么样写才能是在创立新的 post 实例的时候,把 attach.image 上传成功呢? 2.我乖乖的听从指导创建 attach 去

#6 楼 @Rei 1.完成了 carrierwave 的实现图片上传,但是还是不懂为什么之前的没有成功,之前的区别仅仅在于我有了表间的关联,其他的都是一样的. 2.继续 jQuery-File-Upload

#8 楼 @jialezhang 关联的对象的字段表单要用 fields_for

#10 楼 @jialezhang 有 -rails 的那个只是原 jquery 插件的 assets pipeline 包装而已。

#11 楼 @Rei 求问 ruby-china 是桌面处理缓存问题的哈,感觉论坛切换很快 (应该不是服务器的问题吧)

怎么修改图片的名字,名字是 uuid 自动生成的。

You need to Sign in before reply, if you don't have an account, please Sign up first.