Red > Green > Refactor > Red

cycle is based on desire

new と build

自身で改めて

class Cart < ActiveModel
  has_many :line_items
end

class LineItems < ActiveModel
  belongs_to :cart
end

[1]

Cart.new は OK

Cart.build は NG

[2]

c = Cart.new して

c.line_items.new, c.line_items.build は OK

[3] そもそも build は new の alias らしい

https://github.com/rails/rails/blob/master/activerecord/lib/active_record/relation.rb#L111

ちょいちょい挙動がちがうのは、new と build で

最終的に呼んでいるクラスが違うから?

でも、それって alias ではない気が

深いところで build だったら foo, new だったら baz のようなことしてるのかね?


[1]

2.0.0-p353 :001 > nCart = Cart.new
 => #<Cart id: nil, created_at: nil, updated_at: nil> 
2.0.0-p353 :002 > bCart = Cart.build
NoMethodError: undefined method `build' for Cart(id: integer, created_at: datetime, updated_at: datetime):Class
    from /home/matsu/.rvm/gems/ruby-2.0.0-p353@two/gems/activerecord-4.0.0/lib/active_record/dynamic_matchers.rb:22:in `method_missing'
    from (irb):2
    from /home/matsu/.rvm/gems/ruby-2.0.0-p353@two/gems/railties-4.0.0/lib/rails/commands/console.rb:90:in `start'
    from /home/matsu/.rvm/gems/ruby-2.0.0-p353@two/gems/railties-4.0.0/lib/rails/commands/console.rb:9:in `start'
    from /home/matsu/.rvm/gems/ruby-2.0.0-p353@two/gems/railties-4.0.0/lib/rails/commands.rb:64:in `<top (required)>'
    from bin/rails:4:in `require'
    from bin/rails:4:in `<main>'

[2]

2.0.0-p353 :003 > c = Cart.new
 => #<Cart id: nil, created_at: nil, updated_at: nil> 

2.0.0-p353 :004 > c.line_items.new
 => #<LineItem id: nil, product_id: nil, cart_id: nil, created_at: nil, updated_at: nil, quantity: 1> 

2.0.0-p353 :005 > c.line_items.build
 => #<LineItem id: nil, product_id: nil, cart_id: nil, created_at: nil, updated_at: nil, quantity: 1>