augustl (owner)

Revisions

gist: 142674 Download_button fork
public
Public Clone URL: git://gist.github.com/142674.git
Embed All Files: show embed
Text only #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
require 'rubygems'
require 'active_record'
 
ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :dbfile => ":memory:")
silence_stream(STDOUT) do
  ActiveRecord::Schema.define do
    create_table(:posts) {|t| t.string :title }
    create_table(:comments) {|t| t.integer :post_id; t.string :comment }
  end
end
 
class Post < ActiveRecord::Base
  has_many :comments
  accepts_nested_attributes_for :comments
end
 
class Comment < ActiveRecord::Base
  belongs_to :post
  before_save :ping
  
  def ping
    puts "Pinged! `#{comment}'"
  end
end
 
if __FILE__ == $0
  post = Post.new(:title => "This is odd", :comments_attributes => [{:comment => "Yeah, it is."}])
  post.save
  # => Pinged! `Yeah, it is.'
 
  post.comments_attributes = [{:comment => "What what what?"}]
  post.save
  # => Pinged! `Yeah, it is.'
  # => Pinged! `What what what?'
  
  p post.comments
  # => [#<Comment id: 1, post_id: 1, comment: "Yeah, it is.">, #<Comment id: 2, post_id: 1, comment: "What what what?">]
end