2016-08-10 95 views
0

我有一個視圖,列出數據並允許用戶創建新記錄(部分)。問題是,表單存在於索引操作之下,所以如果用戶輸入在重定向時無效,我將丟失表單的數據。Rails 4如何在重定向時保留表單數據

我想保留數據,所以用戶不必再次輸入。

控制器:

def index 
    @instance = Instance.new 
end 

def create 
    w = current_user.workspaces.find_by_id(params[:"..."] 
if w.present? 
    @instance = current_user.workspaces.find_by_id([:"..."]).instances.create(...) 
    [:info] = "Please check your email to activate your account." 
     redirect_to root_url   
    else 
     flash[:info] = "Please check your data" 
     redirect_to root_url 
    end 

end 

index.html.haml

= render :partial => 'partial1' 

partial1.html.haml

= form_for @instance , url: {action: "create"} do |f| 

我知道 '渲染' 保持表單的數據,但這樣做:

def create 
    if something 
     ... 
    else 
     flash[:info] = "Please check your data" 
     render :index 
    end 

end 

我得到的錯誤

在形式上不能包含零或爲空

第一個參數

=的form_for @instance,網址:{行動: 「創造」}做| F |

我該如何解決? 我不想在創建行動初始化@instance,這樣

def create 
... 
flash[:info] = "Please check your data" 
@instance = Instance.create 
render :index 

,因爲我會重複的代碼,這已經是寫在索引操作。


到包起來:

我有具有局部形式,具有複雜控制器的複合索引圖。 我無法呈現:創建操作的索引,因爲我將不得不加載所有索引的實例變量。 如果數據不正確,我無法創建@instance變量,因爲我有一個嵌套窗體。

+0

當我們編寫的「創造」的行動,我們通常會建立一個對象,在這種情況下,一個實例對象,所以,我們通常會做類似@instance = Instance.new(PARAMS [ :instance])在你'創建'動作中,用這個,你已經有了你的變量,而使用'render:index'時的錯誤會消失。 – fanta

+0

'@instance = Instance.new'僅爲表單存儲用戶輸入的實例化@實例。它不是創建一個對象。所以,在你的'controller'中,你必須檢索這個信息,例如params,然後使用'Instance.create'和'save',這樣就不會重複代碼。 – mrvncaragay

+0

如果你想在用戶輸入無效時保留數據,請使用'render index'而不是'redirect_to root_url' – mrvncaragay

回答

0

我不想在創建操作初始化@instance ...

那麼,你應該,因爲你想要一個實例。但是,您應該使用表單中填寫的參數「初始化」一個參數,而不是「創建」一個參數。所以這樣做:

def create 
... 
flash[:info] = "Please check your data" 
@instance = Instance.new(params[:instance]) 
render :index 
+0

問題是我無法初始化一個實例,除非滿足所有要求,因爲我有一個嵌套窗體。我已更新代碼 – Gaston

+0

我已更新代碼aswel。你應該可以做到這一點。通過這樣做,您不會將它保存到數據庫,但是您「記住」了填充的參數。 –

相關問題