gpt4 book ai didi

ruby-on-rails - 播种 has_many :through relationships in Rails 的正确方法

转载 作者:数据小太阳 更新时间:2023-10-29 07:28:29 28 4
gpt4 key购买 nike

我已经通过数据库迁移到 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com