rails carrierwave,一个用户有很多图像

时间:2017-10-25 04:43:01

标签: ruby-on-rails ruby

我用过

rails: 4.2.9
ruby: 2.3.1p112

我创建了用途,景点和attraction_photos模型。我希望每个用户都有很大的吸引力,每个景点都有很多景点照片。吸引创建是有效的,但attraction_photos是空的,文件没有上传成功。

Gemfile

gem 'carrierwave'
gem 'mini_magick'

吸引力照片迁移

class CreateAttractionPhotos < ActiveRecord::Migration
  def change
    create_table :attraction_photos do |t|
      t.integer :attraction_id
      t.string :photo

      t.timestamps null: false
    end
  end
end

用户

class User < ActiveRecord::Base

    has_many :attractions
    ...
end

景点

class Attraction < ActiveRecord::Base
  belongs_to :user
  has_many :attraction_photos, dependent: :destroy

  accepts_nested_attributes_for :attraction_photos
  ...
end

Attraction_photo

class AttractionPhoto < ActiveRecord::Base
  belongs_to :attraction

  mount_uploader :photo, AttractionImageUploader
end

AttractionImageUploader

class AttractionImageUploader < CarrierWave::Uploader::Base

  include CarrierWave::MiniMagick
  storage :file

  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  process resize_to_fit: [800, 800] 

  version :thumb do
    process resize_to_fit: [200, 200]
  end

  version :medium do 
    process resize_to_fill: [400, 400]
  end

  def extension_whitelist
    %w(jpg jpeg gif png)
  end
end

attractions_controller

  def new
    @attractions = Attraction.new
    @attraction_photos = @attractions.attraction_photos.new
  end

  def create
    @attractions = current_user.attractions.build(attraction_params)

    if @attractions.save
      flash[:success] = "success"
      redirect_to attractions_path
    else
      flash[:danger] = @attractions.errors.full_messages
      render action: :new
    end
  end

  private

  def attraction_params
    params.require(:attraction).permit(:name, :longitude, :latitude, :address, :phone, :category_id, attraction_photos: [:photo])
  end

吸引力new.html.erb

<%= form_for(@attractions) do |f| %>
    <div class="form-group">
      <%= f.label :name, t("attraction.name"), class: "col-md-2 control-label" %>
      <div class="col-md-10">
        <%= f.text_field :name, class: "form-control" %>
      </div>
    </div>

    <div class="form-group">
      <%= f.label :attraction_photos, t("attraction.attraction_photo"), class: "col-md-2 control-label" %>
      <div class="col-md-10">
        <%= f.file_field :photo, class: "form-control" %>
      </div>
    </div>

1 个答案:

答案 0 :(得分:0)

我建议你使用https://github.com/nathanvda/cocoon

但如果你不想使用宝石:

像这样:

<%= f.fields_for :attraction_photos do |att_photo| %>
    <%= att_photo.label :photo %>
    <%= att_photo.file_field :photo %>
<% end %>
  • 请记住在新控件的动作中构建引人注目的照片。 @attraction.attraction_photos.build

  • 您应该修复允许的参数 attraction_photos: [:photo]attraction_photos_attributes: [:id, :photo]