Rails 3.2 has_many:as polymorphic,Simple Form,simple_fields_for

时间:2013-06-12 06:47:30

标签: ruby-on-rails simple-form has-many cocoon-gem

尝试在我的产品表单中保存一些图像。我正在考虑让我将images_attributes作为“产品”一部分的参数。当我在控制台中创建这样的参数并创建产品时,图像实际上会保存。

class Product < ActiveRecord::Base
    extend FriendlyId
    friendly_id :name, use: :slugged

    attr_accessible :description, :name, :category_ids, :brand_ids, :image_ids, :images_attributes

    has_many :images, :as => :imageable

    accepts_nested_attributes_for :images
end

class Image < ActiveRecord::Base
    belongs_to :imageable, :polymorphic => true
    attr_accessible :name, :file
    mount_uploader :file, ImageUploader
end

= simple_form_for(@product, :html => {:multipart => true}) do |f|
    = f.error_notification

    .form-inputs
        = f.input :name
        = f.input :description

        = f.association :categories, as: :check_boxes
        = f.association :brands, as: :check_boxes

        = f.association :images

        = simple_fields_for :images do |i|
            = i.input :file, as: :file
            = i.input :name

    .form-actions
        = f.button :submit


# GET /products/new
# GET /products/new.json
def new
    @product = Product.new
    @product.images.build

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @product }
    end
end

{
    "utf8"=>"✓",
    "authenticity_token"=>"vvXZFh9sJivA3i4Y0rx9i/oqLwKByrExgYisfdj/N78=",
    "product"=> {
        "name"=>"sxsad",
        "description"=>"saasd",
        "category_ids"=>[""],
        "brand_ids"=>[""],
        "image_ids"=>[""]
     },

     # should be images_attributes and come straight after image_ids?
    "images"=>{
        "name"=>"sdfsdfsdf"
     },

    "commit"=>"Create Product"
}

一旦我让它为一个图像工作,我将会看到像Cocoon这样的多个图像。任何关于这可能出错的想法都将非常感激:)。

1 个答案:

答案 0 :(得分:2)

你应该写一下:

= f.simple_fields_for :images do |i|