2015-07-12 37 views
2

我已經通過數據庫遷移以具有has_many:通過帖子,類別和分類關係之間的關聯。種子has_many的正確方法:通過Rails中的關係

模式:

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,只能隨機一個寫它。那麼,我怎麼能有一個以上的職位類別?我希望他們默認屬於所有人,然後是其他人。

回答

3

你不能與0的ID的類別,您可以使用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 
+0

太棒了!有效!甚至沒有想到類別不是0.另外,'category:'而不是'category_id'修正了它。謝謝 :) – user3162553

相關問題