3
4

More than 3 years have passed since last update.

【rails】他のモデルのDBにimageを保存する方法

Posted at

記事投稿の理由

保存時に他のモデルに対してデータを保存する方法がわからず苦労したので、備忘録として残します。
今回はcarrierwaveを使用します。

環境

rails 5.0.7
carrierwave

carrierwaveの導入に関しては参考になる記事を記載しておきますので、こちらを参照ください。
https://qiita.com/STHEXA/items/05a492bd9cf4cf31ba98

方法

今回はproductのコントローラーとモデル。
imageのモデルを使用いたします。

実装

バリデーションをかけると保存できなくなるようなので、presence:trueは記載しないで下さい。

models/image.rb
class Image < ApplicationRecord
 belongs_to :product
  # モデルを保存できなくなるのでpresence: trueは記載しない

end
models/product.rb
class Product < ApplicationRecord
  has_many :images
  accepts_nested_attributes_for :images
 #イメージをDB登録するために記載

fields_forを使うことで入れ子のモデル(Image)を表示させることができます。

new.html.haml
 = f.fields_for :images do |image_field|
   = image_field.file_field :image ,class: "upload-image", type: "file"

コントローラーでnewアクションでAddressをbuild(newのリレーション版)をするようにします。
これにより、fields_for内の内容が表示されます。
また、StrongParameterも許可するようにします。fields_forは[引数に与えた名前]_attributesというname属性でフォームを作成するので、images_attributesを許可する必要があります。

Products_controller.rb
class productsController < ApplicationController
  def new
    @product = Product.new
    @product.image.build
  end

  def create
    @item = Item.new(create_params)
      if @item.save
     else
      render= 'new'
  end

  private
  def create_params
    params.require(:item).permit( images_attributes: [:image, :id])
end

参考

下記の記事は非常に丁寧に書かれており、わかりやすかったです。
是非ご一読下さい。

Railsでaccepts_nested_attributes_forとfields_forを使ってhas_many関連の子レコードを作成/更新するフォームを作成
https://ruby-rails.hatenadiary.com/entry/20141208/1418018874

3
4
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
3
4