我已经通过数据库迁移到 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,只属于随机写入的帖子。那么,我如何才能为一个帖子设置多个类别呢?我希望它们默认属于所有人,然后属于其他人。

最佳答案

您不能拥有 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

关于ruby-on-rails - 播种 has_many :through relationships in Rails 的正确方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31364265/

10-12 15:53