What is the difference between build and new on Rails?

前端 未结 5 1579
無奈伤痛
無奈伤痛 2020-12-02 09:11

Can anyone tell me what is the difference between build and new command on Rails?

5条回答
  •  囚心锁ツ
    2020-12-02 09:54

    I observed a difference between .build and .new when using them to create a 'dummy' object for a view form, using a using nested resource.

    .build creates a parent_id .new does not

    Nested Resource example: @list.items (where Item is nested under List)

    @list.items.build ...produces an object with all nil values EXCEPT for list_id.

    Item.new creates a new item object, with all nil values.

    It showed up in my 'show' page when iterating over @list.items Not an issue until I needed @list.items further down same 'show' page in another form, where iteration on @list.items exposed the item (the one produced by .build) that had an associated list_id, but nothing else.

    Some sample outputs below...

    @list.items.build => #


    2.2.3 :002 > Item.all.build => #


    2.2.3 :003 > Item.new => # 2.2.3 :004 >

提交回复
热议问题