Rails build 和new的用法区别


关于build和new的区别:
类有new方法,没有build方法
build应该是属于对象的方面。
build是new一个关联的对象的。
对象和和build处理的对象 关联在一起,
对象保存,build处理的对象作为依附在他上面的对象也会保持。

irb(main):002:0> b = a.comments.new
=> #<Comment:0x00007fc20a28be18 id: nil, commenter: nil, body: nil, article_id: 1, created_at: nil, updated_at: nil>
irb(main):003:0> c = a.comments.build
=> #<Comment:0x00007fc20a199d98 id: nil, commenter: nil, body: nil, article_id: 1, created_at: nil, updated_at: nil>
irb(main):004:0> d = Comment.new
=> #<Comment:0x00007fc20a28e7f8 id: nil, commenter: nil, body: nil, article_id: nil, created_at: nil, updated_at: nil>
irb(main):005:0> e = Comment.build
/home/hw/.rbenv/versions/3.1.1/lib/ruby/gems/3.1.0/gems/activerecord-7.0.3/lib/active_record/dynamic_matchers.rb:22:
in `method_missing': undefined method `build' for Comment:Class (NoMethodError)                                              

build的用例

new_user = User.new
=> #<User id: nil, name: nil, state: nil, created_at: nil, updated_at: nil>

post = new_user.posts.build
=> #<Post id: nil, user_id: nil, active: nil, created_at: nil,updated_at: nil>

comment = post.comments.build
=> #<Comment id: nil, post_id: nil, created_at: nil, updated_at: nil>

new_user.save
=> true

new_user
=> #<User id: 4, name: nil, state: nil, created_at: “2009-02-1616:17:35”, updated_at: “2009-02-16 16:17:35”>

post
=> #<Post id: 4, user_id: 4, active: nil, created_at: “2009-02-1616:17:35”, updated_at: “2009-02-16 16:17:35”>

comment
=> #<Comment id: 1, post_id: 4, created_at: “2009-02-16 16:17:35”,updated_at: “2009-02-16 16:17:35”>

阅读量: 392
发布于:
修改于: