种子has_many的正确方法:通过Rails中的关系

时间:2015-07-12 04:06:54

标签: ruby-on-rails ruby

我已经通过数据库迁移到了一个has_many:通过帖子,类别和分类关系之间的关联。

架构:

create_table "categories", force: :cascade do |t|
  t.string   "title"
  t.integer  "subscribers"
  t.integer  "mod"
  t.text     "description"
  t.datetime "created_at",  null: false
  t.datetime "updated_at",  null: false
end


create_table "categorizations", force: :cascade do |t|
  t.integer  "category_id"
  t.integer  "post_id"
  t.datetime "created_at"
  t.datetime "updated_at"
end

create_table "posts", force: :cascade do |t|
  t.string   "title"
  t.datetime "created_at",              null: false
  t.datetime "updated_at",              null: false
  t.integer  "user_id"
  t.text     "content"
  t.integer  "category_id"
end

型号:

class Categorization < ActiveRecord::Base 
  belongs_to :category
  belongs_to :post
end 

class Category < ActiveRecord::Base
  has_many :categorizations
  has_many :posts, :through => :categorizations
end


class Post < ActiveRecord::Base
  has_many :categorizations
  has_many :categories, :through => :categorizations
  has_many :comments, dependent: :destroy  
end

种子

TITLES = %w[sports politics religion programming writing hunting all]       

# Create Categories 
10.times do |n|
  subscribers = rand(1..99)
  description = Faker::Lorem.paragraph(30)

  Category.create!(
    title:       TITLES.pop,
    subscribers: subscribers,
    description: description
  )
end

# Create Posts 
100.times do |n|
  title       = Faker::Lorem.sentence  
  content     = Faker::Lorem.paragraph(30)
  category_id = rand(1..10)

  post = Post.create!(
    title:   title,
    content: content, 
)

post.categorizations.create(
    category_id: 0 
)
post.categorizations.create(
    category_id: rand(2..10) 
)
end 

但是发生的事情是帖子不属于0,只属于随机写的帖子。那么,我怎样才能为帖子提供多个类别?我希望他们默认属于所有人,然后是其他人。

1 个答案:

答案 0 :(得分:6)

您不能拥有ID为0的类别。您可以使用1,但替代方案可能是:

categories = (1..10).to_a.map do |n|
  subscribers      = rand(1..99)
  description        = Faker::Lorem.paragraph(30)

  Category.create!(
    title:          TITLES.pop,
    subscribers:    subscribers,
    description:    description
  )
end

# Create Posts 
100.times do |n|
  title       = Faker::Lorem.sentence  
  content     = Faker::Lorem.paragraph(30)

  post = Post.create!(
    title:        title,
    content:      content, 
  )


  post.categorizations.create(
    category: categories[0] 
  )

  post.categorizations.create(
    category: categories[rand(categories.size)] 
  )
end