Neil Hoff
Neil Hoff

Reputation: 2075

What is the "Rails Way" to create the related row at the time the other row is created in Ruby on Rails

I have two tables: Lessons and Pages

When a new lesson is created I want the first page to be created at the same time. The first page will have:

Upvotes: 0

Views: 40

Answers (1)

Jeremy Roman
Jeremy Roman

Reputation: 16355

Something like this will do the trick:

class Lesson < ActiveRecord::Base
  has_many :pages
  before_create :create_first_page

  def create_first_page
    if pages.empty?
      pages.build(:title => title)
    end
  end
end

Upvotes: 1

Related Questions