使用嵌套属性JSON /数组类型

时间:2015-08-20 12:30:41

标签: ruby-on-rails carrierwave simple-form strong-parameters ruby-on-rails-4.2

我试图通过CarrierWave找出多次上传,并能够通过accepts_nested_attributes_for :car_images, reject_if: :all_blank, allow_destroy: true

从不同的控制器和模型中保存它

我使用CarrierWave并且我的CarImage模型包含图像的JSON类型列。

创建新车CarsController#New时,我希望能够:

  • 写标题(工作)
  • 编写说明(工作)
  • 通过嵌套表单上传多个图片(工作)

尝试保存附有图像的新车时出现以下错误消息:

Unpermitted parameter: images

参数:

Started POST "/cars" for 127.0.0.1 at 2015-08-20 22:04:19 +1000
Processing by CarsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"GEAGEAKQw3foK7/1+kGMhTVArqRaC8gHaHjHAtef0zmJDr2i5U9TictQ9kj3A==", "car"=>{"title"=>"Ford", "description"=>"Mustang", "car_images_attributes"=>{"0"=>{"images"=>[#<ActionDispatch::Http::UploadedFile:0x007fbec0dfa5a8 @tempfile=#<Tempfile:/var/folders/r0/24wrt39d1kl37mmymjjmmxy45000gn/T/RackMultipart20150820-12757-1e4egob.jpg>, @original_filename="ford-mustang-front.jpg", @content_type="image/jpg", @headers="Content-Disposition: form-data; name=\"car[car_images_attributes][0][images][]\"; filename=\"ford-mustang-front.jpg\"\r\nContent-Type: image/jpg\r\n">, #<ActionDispatch::Http::UploadedFile:0x007fbec0dfa508 @tempfile=#<Tempfile:/var/folders/r0/24wrt39d1kl37mmymjjmmxy45000gn/T/RackMultipart20150820-12757-6pckqd.png>, @original_filename="ford-mustang-back.jpg", @content_type="image/png", @headers="Content-Disposition: form-data; name=\"car[car_images_attributes][0][images][]\"; filename=\"ford-mustang-back.jpg\"\r\nContent-Type: image/jpg\r\n">]}}}, "commit"=>"Create Car"}

我不确定它是否与表单有关,但是当将多个文件保存为数组时,它应该具有唯一索引吗? params日志看起来像保存了第一个索引中的所有图像:car[car_images_attributes][0][images][]\

我的CarsController允许以下参数:

    def car_params
      params.require(:car).permit(:title, :description, 
      car_images_attributes: [:id, :car_id, :image])
    end

car_images_attributes允许:image属性为JSON / Array类型。

非常感谢任何见解。

汽车模型

# == Schema Information
#
# Table name: cars
#
#  id          :integer          not null, primary key
#  title       :string           default(""), not null
#  description :text             default("")
#  price       :float            default(0.0)
#  created_at  :datetime         not null
#  updated_at  :datetime         not null


class Car < ActiveRecord::Base
  has_many :car_photos
  accepts_nested_attributes_for :car_images, reject_if: :all_blank, allow_destroy: true

end

汽车图像模型

# == Schema Information
#
# Table name: car_images
#
#  id          :integer          not null, primary key
#  image       :json             default({}), not null
#  title       :string           default(""), not null
#  car_id      :integer
#  created_at  :datetime         not null
#  updated_at  :datetime         not null
#

class CarImages < ActiveRecord::Base
  belongs_to :car
  mount_uploader :image, ImageUploader
end

汽车控制器

class CarsController < ApplicationController
  before_action :set_car, only: [:show, :edit, :update, :destroy]

  def show
  end

  def new
    @car = Car.new
    @car.car_images.build
  end

  def edit
  end

  def create
    @car = Car.new(car_params)

    respond_to do |format|
      if @car.save    
        format.html { redirect_to @car, notice: 'Car was successfully created.' }
        format.json { render :show, status: :created, location: @car }
      else
        @car.car_images.build # ensures car_image form object exists

        format.html { render :new }
        format.json { render json: @car.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
    respond_to do |format|
      if @car.update(car_params)
        format.html { redirect_to @car, notice: 'Car was successfully updated.' }
        format.json { render :show, status: :created, location: @car }
      else
        format.html { render :new }
        format.json { render json: @car.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @car.destroy
    respond_to do |format|
      format.html { redirect_to root_path, notice: 'Car was successfully destroyed.'}
      format.json { head :no_content }
    end
  end

  private

    def set_car
      @car = Car.find_by_id(params[:id])
    end

    def car_params
      params.require(:car).permit(:title, :description, car_images_attributes: [:id, :car_id, :images])
    end
end

汽车表格

<%= simple_form_for @car, html: { multipart: true } do |f| %>

  <%= f.input :title  %>
  <%= f.input :description, as: :text %>

  <%= f.simple_fields_for :car_images do |image| %>
    <% if image.object.new_record? %>
      <%= image.input :images, as: :file, required: false, error: false, input_html: { multiple: true } %>
    <% end %>
  <% end %>

  <%= f.button :submit %>
<% end %>

非常感谢任何见解。

我正在考虑迭代参数[:car_images] [&#39;图像&#39;]并创建CarImage记录,但我认为这可能不是最好的方法,并希望能够添加没有图像的汽车记录,如果没有附加图像,这将失败,除非进行额外的检查(零)。

更新

我已经尝试了数据库列类型JSONTEXT (as an array)但仍有问题。如果我将其更改为普通STRING,则可以使用,但它不是照片的集合。

0 个答案:

没有答案