我正在构建一个将应用程序与许多不同类别关联的应用程序。例如,我有一个帖子,需要能够通过csv导入通过rake任务将其分配到体育,新闻和科学类别。Rails csv与协会的导入
我的问题是如何将多个category_ids的数组导入到Post模型中?我有它的工作,我可以手动创建一个新的职位,并指定多个类别的职位,但我很困惑,如何通过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中,我有“1,2,3”代表3个不同类别的ID,但只记录第一个ID。另外,为什么你使用.new vs .create?谢谢您的帮助 – b1akely