samedi 11 juillet 2015

Proper way to seed has_many :through relationships in Rails

I've migrated by database to have a has_many :through association between Posts, Categories and the relationship of Categorizations.

Schema:

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

Models:

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

Seeds

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 

But what happens is that the posts don't belong to 0, only to the random one that writes over it. So, how can I actually have more than one category for a post? I want them to belong to all by default and then to others.

Aucun commentaire:

Enregistrer un commentaire