Skip to content

Instantly share code, notes, and snippets.

@asv
Created September 19, 2013 10:20
Show Gist options
  • Save asv/6621573 to your computer and use it in GitHub Desktop.
Save asv/6621573 to your computer and use it in GitHub Desktop.
class Bar < ActiveRecord::Base
attr_accessible :name
has_many :bazs, autosave: true
end
class Baz < ActiveRecord::Base
belongs_to :bar
attr_accessible :name
end
$ rails c
irb(main):001:0> bar = Bar.first
Bar Load (0.4ms) SELECT "bars".* FROM "bars" LIMIT 1
=> #<Bar id: 1, name: "FooBar", created_at: "2013-09-19 09:28:55", updated_at: "2013-09-19 09:28:55">
irb(main):002:0> baz = bar.bazs.first
Baz Load (0.5ms) SELECT "bazs".* FROM "bazs" WHERE "bazs"."bar_id" = 1 LIMIT 1
=> #<Baz id: 1, name: "Baz 1", bar_id: 1, created_at: "2013-09-19 09:28:55", updated_at: "2013-09-19 09:37:42">
irb(main):003:0> baz.name = 'New Baz'
=> "New Baz"
irb(main):004:0> bar.save!
(0.2ms) BEGIN
(0.1ms) COMMIT
=> true
Bar.create do |bar|
bar.name = 'FooBar'
bar.bazs.build do |baz|
baz.name = 'Baz 1'
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment