1
我用回形針和Rails 4上傳圖片。目標是允許用戶在編輯頁面上添加新圖像。目前用戶可以查看與模型相關的當前圖像並將其刪除,但我希望用戶能夠在同一頁面上上傳新圖像。Rails的回形針和:編輯頁面上傳新文件
由於表單提交給controller#update
我不知道如何建立相關的模型的實例變量的新形象。
= form_for @car, html: { multipart: true, id: "fileupload", "data-abide" => true } do |f|
...
%h4
New files
= f.fields_for :uploads do |upload_fields|
= upload_fields.file_field :upload
- unless f.object.new_record?
%h4
Old Files
= f.fields_for :uploads do |upload_fields|
.thumb
= link_to image_tag(upload_fields.object.upload.url(:thumb)), upload_fields.object.upload.url(:original)
= upload_fields.check_box :_destroy
Car.rb
class Car < ActiveRecord::Base
has_many :uploads, dependent: :destroy
validates :make, :model, :year, :seats, :transmission, :drive, :interior, :exterior, presence: true
accepts_nested_attributes_for :uploads, allow_destroy: true
# http://stackoverflow.com/questions/2672744/rails-activerecord-find-all-users-except-current-user/2674308#2674308
scope :without_car, lambda{|car| car ? {conditions: ["id != ?", car.id]} : {} }
end
Upload.rb
class Upload < ActiveRecord::Base
belongs_to :car
has_attached_file :upload, styles: { medium: '300x300>', thumb: '100x100>' }
validates_attachment_content_type :upload, :content_type => /\Aimage\/.*\Z/
validates_attachment_presence :upload
end
你可以分享你的車,上傳模型關聯。我假定上傳模型具有has_attached_file關聯。 – blotto
問題更新 – Patrick