我希望您能为每个租赁模型添加多张图片,但我不能在我的租赁控制器上保存它们。
我使用了Carrierwave gem来上传它们。
controllers/renters_controller.rb
controllers/renters_controller.rb
def create
@renter = Renter.new(renter_params)
if @renter.save
gflash notice: "Le loueur a bien été enregistré"
redirect_to '/'
else
gflash :now, notice: "Une erreur est survenue."
render :new
end
end
def renter_params
params.require(:renter).permit(:name, :address, :website, :email, :phone, :review, :latitude, :longitude, :user_id, pictures: [])
end
models/renter.rb
class Renter < ActiveRecord::Base
belongs_to :user
geocoded_by :address
after_validation :geocode
reverse_geocoded_by :latitude, :longitude
after_validation :reverse_geocode # auto-fetch address
mount_uploader :image, ImageUploader
mount_uploader :pictures; PicturesUploader
end
我有一个上传文件
uploaders/pictures_uploader.rb
在我的视图表单上
views/renters/_form.html.haml
= form_for(@renter, :hmtl => {:multipart => true}) do |f|
- if @renter.errors.any?
#error_explanation
%h2
= pluralize(@renter.errors.count, "error")
prohibited this renter from being saved:
%ul
- @renter.errors.full_messages.each do |message|
%li= message
.row
.large-6.medium-6.columns
= f.text_field :name, placeholder: t('.name')
.large-6.medium-6.columns
= f.text_field :website, placeholder: t('.website')
.row
.large-6.medium-6.columns
= f.text_field :email, placeholder: t('.email')
.large-6.medium-6.columns
= f.text_field :phone, placeholder: t('.phone')
.row
.large-6.medium-6.columns
= f.text_field :address, placeholder: t('.address')
.large-3.medium-3.columns
= f.text_field :latitude, placeholder: :latitude
.large-3.medium-3.columns
= f.text_field :longitude, placeholder: :longitude
.row
= f.file_field :pictures, multiple: true, accept: "image/jpeg, image/jpg, image/gif, image/png"
.row
.large-12.columns.large-centered
.large-12.columns.large-centered
= f.submit :value => 'Valider', :class => 'default button'
以及我的错误信息
Processing by RentersController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"3YfZtWpnDb03yRs1HVp11jJSE15mm6PLOyIKxeJTcoOWsBaFNR/LYYYkD921Zzy5Urb9wgV5tpyhwG8oVAvZPw==", "renter"=>{"name"=>"Miami boat rental", "website"=>"", "email"=>"", "phone"=>"", "address"=>"", "latitude"=>"", "longitude"=>"", "pictures"=>[#<ActionDispatch::Http::UploadedFile:0x007f8ab9728530 @tempfile=#<Tempfile:/var/folders/1d/5fhghxdx5hz_7clwv4gkbwm80000gn/T/RackMultipart20160225-2432-sy0x2h.png>, @original_filename="corse_catamarans.png", @content_type="image/png", @headers="Content-Disposition: form-data; name=\"renter[pictures][]\"; filename=\"corse_catamarans.png\"\r\nContent-Type: image/png\r\n">]}, "commit"=>"Valider"}
Completed 500 Internal Server Error in 9ms (ActiveRecord: 0.0ms)
TypeError (no implicit conversion of nil into String):
app/controllers/renters_controller.rb:43:in `create'
我认为问题是由于图片的JSON格式,但这只是我的感觉。提前谢谢。