投稿をさまざまなカテゴリに関連付けるレールアプリケーションを構築しています。たとえば、私は投稿を持っており、rakeタスクを介してcsv importを通してスポーツ、ニュース、科学のカテゴリに割り当てることができる必要があります。Rails csv import with associations
私の質問は、複数のcategory_idsの配列を投稿モデルにインポートする方法です。私は手動で新しい投稿を作成し、投稿に複数のカテゴリを割り当てることができるところで働いていますが、私はcsvを通じてこれを完了する方法について混乱しています。私はこれを達成するための最良の方法を考え出す助けが必要です。ここで
は、私がこれまで持っているものです。
スキーマ
create_table "posts", force: :cascade do |t|
t.string "name"
t.text "description"
end
create_table "styles", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "post_id"
t.integer "category_id"
end
create_table "categories", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
Post.rb
class Post < ApplicationRecord
has_many :styles
has_many :categories, through: :styles
end
Category.rb
class Category < ApplicationRecord
has_many :styles
has_many :posts, through: :styles
end
Style.rb
class Style < ApplicationRecord
belongs_to :post
belongs_to :category
end
のRakeタスク
require 'csv'
require 'open-uri'
namespace :post_import do
desc "Import posts daily"
task posts: :environment do
filename = File.join Rails.root, "posts.csv"
counter = 0
CSV.foreach(filename) do |row|
name, category, description = row
post = Post.create(name: name, category_ids: category, description: description)
counter += 1 if post.persisted?
end
puts "Imported #{counter} [posts]"
end
end
これが適切な答えである理由を説明します。コードを外すのではなく、教育に役立ちます。 –
投稿を複数のカテゴリに割り当てるにはどうすればよいですか?たとえば、カテゴリー行のcsvには、3つの別々のカテゴリーのIDを表す「1,2,3」がありますが、最初のIDだけが記録されています。また、なぜ新しい.vs .createを使うのですか?助けてくれてありがとう – b1akely