0

我不知道什麼是應對3級深,嵌套形式對控制器更深3深嵌套形式

一個例子,最好的辦法:

店控制器

def new 
    @user = current_user 
    @shop = @user.build_shop 
    @type = @shop.build_type 
end 

def create 
    @user = current_user 
    @shop = @user.build_shop(params[:shop]) 
    @type = shop.build_type(params[:type]) 
    if @shop.save  
    flash.now[:success] = "blah" 
    render :show 
    else 
    render :new 
    end 
end  

回答

2

如果accept_nested_attributes_for變得難以實現,那麼您的構建方法實際上是您唯一的選擇,而無需對代碼進行更深層次的重構。

1

我建議你閱讀ActiveRecord的accepts_nested_attributes_for方法。它將在大多數情況下消除您所有的build_...(...)方法的需求,並且使用嵌套表單精美地運行。

+0

在這裏同意Deefour,但Rails世界充滿了關於做超過兩層深的嵌套屬性的警告。在你走得太遠之前,建議你在Rails上深入嵌套的模型中進行大量搜索。 – 2012-02-23 07:32:20

+0

是的,我同意你的觀點,但有時你必須拋棄那些不起作用的優秀方案。 – dcalixto 2012-02-23 08:31:26