12
9

More than 5 years have passed since last update.

[Rails] Carrierwaveでformを使わずに画像を保存する方法いろいろ

Last updated at Posted at 2017-01-19

Carrierwave, モデルとの関連付けも簡単で便利ですが、
formを使わないケースについてあまり紹介されていないのでメモ

has_one のパターン

user.rb
has_one :thumbnails
mount_uploader :image, ThumbnailUploader
thumbnail.rb
belongs_to :user

formを使わずに画像保存

user_controller.rb
@user = User.new(name: "John")
@user.image = File.open("/path/to/file")
@user.save

バイナリデータではなく、URLからダウンロードして保存

@user = User.create(name: "John")
@user.remote_image_url = "http://placehold.it/200x200"
@user.save

has_many のパターン

formなら、accepts_nested_attributes_forを使えばいいが、使わないと少し面倒

user.rb
has_many :thumbnails
thumbnail.rb
belongs_to :user
mount_uploader :image, ThumbnailUploader

formを使わずに画像保存

user_controller.rb
@user.create(name: "John")
@user.save

thumb = Thumbnail.new(user_id: @user.id)
thumb.image = File.open("/path/to/file")

@user.thumbnails << thumb
@user.save

バイナリデータではなく、URLからダウンロードして保存

user_controller.rb
@user.create(name: "John")
@user.save

thumb = Thumbnail.new(user_id: @user.id)
thumb.remote_image_url = "http://placehold.it/200x200"

@user.thumbnails << thumb
@user.save

複数画像の場合、それぞれ2回saveしなければならないのは気持ち悪い・・
もっとスマートなやり方ご存知の方いましたらご教授くださいませm(__)m

12
9
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
12
9