【问题标题】:Spree: Create new asset failure狂欢:创造新的资产失败
【发布时间】:2014-09-24 18:55:18
【问题描述】:

我正在尝试为 Spree 2.3(设计师)中的第三个角色创建自定义表单。设计师创建新产品和变体,然后上传该变体的图像。到目前为止,我的努力都是徒劳的。

如何为变体创建新资产?

错误

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

请求参数

{"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"}

控制器

#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

查看

<%= 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 %>

【问题讨论】:

  • 所以您要在 Image 类中定位 :attachment?
  • 在资产类别中,是的。或者这就是数据库表的读取方式。

标签: ruby-on-rails ruby-on-rails-4 spree ruby-2.1


【解决方案1】:

在具有图像的模型中创建以下关联:

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

这就是 Variant 模型具有 :images 的方式,请通过bundle open spree 获取更多信息。

然后创建一个嵌套表单来创建新的附件,我更喜欢simple_form

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

或者更简单的方法是在模型中包含回形针has_attached_file 方法。

以下来自图像模型,只是为了让您了解 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' }

根据需要进行定制。

希望对您有所帮助!

【讨论】:

  • 看起来该关联已在 Spree 中设置。我应该在装饰器中重写它吗?否则,我不确定您的代码。看起来这意味着资产 has_many Images?我尝试将这种技术用于 'form_for @variant...fields_for :images' 并产生相同的错误消息。
  • 哪个型号的装饰器?您无需在 spree 中向现有模型添加任何内容,因此无需在此处使用装饰器,您收到的错误消息是什么?
  • 相同:未知属性附件
  • 我所指的装饰器是关于您的关联设置建议。据我所知,这应该是 Variant 模型。
  • 您想向 Variant 模型添加什么?我看不到你的设置,所以有点难以理解
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-16
  • 1970-01-01
相关资源
最近更新 更多