1

I am trying to create a custom form for a third role in Spree 2.3 (Designer). The designer creates a new product and variant, then uploads an image for that variant. My efforts have so far been in vain.

How can I create a new asset for a variant?

Error

ActiveRecord::UnknownAttributeError in Designers::SpreeAssetsController#create
unknown attribute: attachment
Extracted source (around line #11):
def create      
  @asset = Spree::Asset.new(asset_params) #line 11
  ...
end

Request parameters

{"utf8"=>"✓",
"authenticity_token"=>"XXX=",
"asset"=>{"attachment"=>#<ActionDispatch::Http::UploadedFile:0x0000010f6c34b8 @tempfile=#<Tempfile:/var/folders/xk/r14w_thd2bn8vxch294zzn040000gn/T/RackMultipart20140731-5542-fgfzhn>,
@original_filename="DSCN0220.JPG",
@content_type="image/jpeg",
@headers="Content-Disposition: form-data; name=\"asset[attachment]\"; filename=\"DSCN0220.JPG\"\r\nContent-Type: image/jpeg\r\n">},
"commit"=>"Create"}

Controller

#app/controllers/designers/spree_assets_controller.rb
def create      
  @asset = Spree::Asset.new(asset_params)
...
end

private

def asset_params
  params.require(:asset).permit(:attachment)
end

View

<%= form_for @asset, url: designers_spree_assets_path, method: :post do |f| %>
  <%= f.label :attachment, "Upload image" %></br>
  <%= f.file_field :attachment %></br>
  <%= f.submit 'Create' %>
<% end %>
4

1 回答 1

1

Create the following association in the model, that has images:

has_many :images, :as => :viewable, :order => :position, :dependent => :destroy, :class_name => "Spree::Image"

This is how the Variant model has :images, do bundle open spree for more info.

Then create a nested form to create new attachment, I prefer simple_form

= simple_form_for @asset, :html => {:multipart => true } do |m|
  = m.simple_fields_for :images do |p|
    = p.file_field :attachment

Or a simpler way of doing it would be to include paperclips has_attached_file method in your model.

The following is from the Image model, just to give you an idea how product images are processed in Spree.

has_attached_file :attachment,
                  :styles => { :mini => '48x48>', :small => '100x100>', :product => '240x240>', :large => '600x600>' },
                  :default_style => :product,
                  :url => '/spree/products/:id/:style/:basename.:extension',
                  :path => ':rails_root/public/spree/products/:id/:style/:basename.:extension',
                  :convert_options => { :all => '-strip -auto-orient' }

Customize as needed.

Hope it helps!

于 2014-08-01T17:50:20.323 回答