1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Rails】関連付けされたモデルのCSVインポートの方法は?

Last updated at Posted at 2018-08-19

Item(商品)登録時に親モデルであるShop(店舗)、子モデルであるship_date(出荷日)を同時に一括でCSVインポートしたいと考えています。

現状、shop_idを含めたアップロードまでは成功しましたが、子モデルである「ship_date(出荷日)」を含める方法で行き詰まっています。

もしご存知でしたらご教示頂けますと嬉しいです!

item.rb
belongs_to :shop
has_many   :ship_date

  def self.import(shop, file)
    CSV.foreach(file.path, headers: true) do |row|
      item = find_by(id: row["id"]) || new
      shop.items.create! row.to_hash.slice(*updatable_attributes)
    end
  end

  def self.updatable_attributes
    ["name", "kana", "price"]
  end
items_controller.rb
  def import
    Item.import(@shop, params[:file])
    redirect_to root_url, notice: "商品を一括で追加しました。"
  end
1
0
1

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?