LoginSignup
23
21

More than 5 years have passed since last update.

CarrierWaveとSimpleFormを使ってネストした複数ファイルを登録する

Last updated at Posted at 2016-01-23

意外と悩んでいる人がいるようなので、carrierwaveとsimple_formは既に利用されていることを前提として、modelとcontrollerとviewについて簡単に記載する。
ちなみにroutesは以下のような感じと仮定している。
resources :images, only: %w(new create edit update destroy)

modelについて

仮定として、1つのユーザーに複数の画像が紐づくと考える。

app/models/user.rb
class User < ActiveRecord::Base
  has_many :images, dependent: :destroy
  accepts_nested_attributes_for :images, allow_destroy: true
app/models/image.rb
class Image < ActiveRecord::Base
  belongs_to :user
  mount_uploader :user_image, ImageUploader

user:imageは1:多

controllerについて

app/controllers/users_controller.rb
class UsersController < ApplicationController
  def new
    @user = User.new
    @user.images.build
    respond_to do |format|
      format.html
    end
  end

  def create
    @user = User.new(user_params)
    respond_to do |format|
      if @user.save
        format.html { redirect_to hogehoge_url, notice: 'ユーザーを新規追加しました。' }
      else
        format.html { render action: 'new' }
      end
    end
  end

  def edit
    @user = User.where(id: params[:id]).first
    @user.images.build
    respond_to do |format|
      format.html
    end
  end

  def update
    @user = User.where(id: params[:id]).first
    respond_to do |format|
      if @user.update_attributes(user_params)
        format.html { redirect_to hogehoge_url, notice: 'ユーザーを更新しました。' }
      else
        format.html { render action: 'edit' }
      end
    end
  end

  def destroy
    user = User.where(id: params[:id]).first

    respond_to do |format|
      if user.destroy
        format.html { redirect_to hogehoge_url}
      else
        format.html { render action: 'edit' }
      end
    end
  end

private
  def user_params()
    params.require(:user).permit( \
      :name \
      ,images_attributes:[\
        :id \
        ,:user_image \
        ,:_destroy
      ]
    )
  end
end

viewについて

new.html.hamlやedit.html.hamlではusers/_form.html.hamlを読み込む。
_form.html.hamlは以下のような感じ。

users/_form.html.haml
= simple_form_for([@user], html: {multipart: true, class: 'form-horizontal', wrapper: :horizontal_form}) do |f|
  = f.error_notification

  = f.input :name
  - @user.images.each do |image|
    = f.simple_fields_for :images, image do |if|
      - if image.user_image?
        = image_tag image.user_image.to_s
        = if.input :_destroy, as: :boolean, label: "削除"
      - else
        = if.input :user_image, label: "画像"


23
21
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
23
21