3

试图在我的产品表单中保存一些图像。我期待参数,我将 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 这样的多张图像。任何关于这可能出错的想法将不胜感激:)。

4

1 回答 1

2

你应该简单地写:

= f.simple_fields_for :images do |i|
于 2013-06-12T11:07:57.457 回答