2010-11-16 74 views
0

我需要建立在軌多編輯表單,像這樣多編輯表單:如何創建軌道

<form> 
<input type='text' name='input1'></input> 
<input type='text' name='input2'></input> 
<input type='text' name='input3'></input> 
<input type='text' name='input4'></input> 
<input type='text' name='input5'></input> 
<br> 
<input type='text' name='input1'></input> 
<input type='text' name='input2'></input> 
<input type='text' name='input3'></input> 
<input type='text' name='input4'></input> 
<input type='text' name='input5'></input> 
<br> 
<input type='text' name='input1'></input> 
<input type='text' name='input2'></input> 
<input type='text' name='input3'></input> 
<input type='text' name='input4'></input> 
<input type='text' name='input5'></input> 
<br> 

...等等,那麼「<submit>」按鈕會在最後。點擊最後的提交按鈕應該收集所有的值並在控制器中解析它們。

我只需要知道如何在視圖中生成多編輯表單。另外,每一行都是唯一的;我還需要知道如何爲我猜測的每個輸入標籤分配一個唯一標識符;我確實有一個我可以使用的唯一ID值。

回答

0

這是微不足道的完成,但我們需要更多的信息。這些字段如何與您的模型相關聯?這是一個有很多領域的模型,模型或其他東西的很多實例嗎?


你想在這種情況下,做的是使用表單生成器。它將根據命名約定生成輸入字段,當它到達控制器時將被解析爲更有用的格式。因爲我不知道你的模型的信息,我會用一個假設的例子:

class Post < ActiveRecord::Base 
    attr_accessible :title, :body, :author, :published_at 
end 

使用form_for幫助創建表單。它會給你一個formbuilder對象來創建輸入字段。

<% form_for :post do |f| -%> 
    <p> 
    <%= f.label :title %> 
    <%= f.text_field :title %> 
    </p> 
    <p> 
    <%= f.label :body %> 
    <%= f.text_area :body %> 
    </p> 
    <p> 
    <%= f.label :author %> 
    <%= f.text_field :author %> 
    </p> 
    <p> 
    <%= f.label :published_at %> 
    <%= f.datetime_select :published_at %> 
    </p> 
<% end -%> 

使用助手的主要優點是它產生輸入的name屬性。由於body屬於post的表單,因此它將被賦予名稱屬性post[body]。這些屬性將被分解成以下散列:

:post => { 
    :title => "This is the title", 
    :body => "this is the body", 
    :author => "John Doe", 
    :published_at => "Mon Nov 15 2010 19:23:40 GMT-0600 (CST)" 
} 

這意味着你不需要手動領域複製到一個模型。您可以直接將它傳遞給Model#new方法:

@post = Post.new(params[:post]) 

然後執行您的驗證檢查。當你開始在另一個模型中嵌套模型時,這個約定變得不可或缺。

See here更全面的指導形成幫手。

+0

與許多領域的一個模型。 – 2010-11-16 01:00:48