2013-11-27 12 views
0

目前,我有以下我的應用程序正常工作:Rails的:需要多選擇窗體以在單獨的行提交數據

<%= f.fields_for :types do |builder| %> 
<p> 
<%= builder.select(:name, [['Type A', 'Type A'], 
['Type B', 'Type B'], 
['Type C', 'Type C'], 
['Type D', 'Type D'], 
['Type E', 'Type E'] 
],{ :prompt => "Please select"}, 
{ :multiple => true, :size => 5 } 
) %> 
</p> 
% end %> 

控制器

def new 
@task = Task.new 
1.times { @task.types.build } 
end 

型號型號

class Type < ActiveRecord::Base 
belongs_to :task 
accepts_nested_attributes_for :task 
attr_accessible :name, :task_attributes 
end 

任務模型

class Task < ActiveRecord::Base 
has_many :types, :dependent => :destroy 
accepts_nested_attributes_for :types 
attr_accessible :types_attributes 
end 

我的問題是,提交一切順利的信息時將在類型表中的同一行,「名」字段 - 我需要它來創建不同行類型表。

我需要這個解決方案http://forums.phpfreaks.com/topic/195729-multiple-select-drop-down-data-saved-to-mysql-how/但Rails的

我可以得到不同的行使用文本字段與下面的代碼創建:

<%= f.fields_for :types do |builder| %> 
<p> 
<%= builder.label :name, "Type Name" %><br /> 
<%= builder.text_field :name %> 
<%= builder.check_box :_destroy %> 
<%= builder.label :_destroy, "Remove Chore" %> 
</p> 
<% end %> 

控制器

def new 
@task = Task.new 
3.times { @task.types.build } 
end 

任何援助將不勝感激。

+0

不知道你的模型的關聯設定,我的猜測是,你要fields_for :類型 – davidfurber

+0

上面是一個錯字(現在我已經在上面修改了),但不幸的是 - 仍然是同樣的問題 - 它向「類型」表提交數據(這是一件好事),沒有任何問題 - - 但所有的數據放在'名稱'單元格的一行---我需要分離每行的費率行只有一個條目在名稱字段中---如果我使用單獨的文本字段,這將非常有效--- – user1648020

+0

Doh!基本的問題是,你無法使用字段和嵌套屬性完成你想要的。嘗試刪除它並使集合選擇轉到type_ids。 – davidfurber

回答

0

這裏是我的一個項目的例子:

class Manuscript < ActiveRecord::Base 
    has_many :readerships 
    has_many :editors, :through => :readerships 
end 

class Readership < ActiveRecord::Base 
    belongs_to :manuscript 
    belongs_to :editor 
end 

class Editor < ActiveRecord::Base 
end 

= form_for resource do |form| 
    = form.collection_select :editor_ids, available_editors, :id, :name, {}, {:multiple => true, :size => 2} 

這裏是上述collection_select的HTML:

<input name="manuscript[editor_ids][]" type="hidden" value=""> 
<select id="manuscript_editor_ids" multiple="multiple" name="manuscript[editor_ids][]" size="2"> 
    <option value="3">Dr. Bob Johnson</option> 
    <option selected="selected" value="4">John Salamandro</option> 
    <option selected="selected" value="1">Erasmus Bielowicz</option> 
</select> 
+0

大衛。我想我越來越近了。我建立了一個HMT關係 - 我有任務(這就像你的手稿) - 我有類型(這就像你的讀者) - 我有顏色(就像你的編輯) - 當我把它放在任務表單<%= form_for:types do | form | %> <%=表格。collection_select:color_ids,description,:id,:name,{},{:multiple => true,:size => 2}%> <% end %> - 我得到這個錯誤消息undefined局部變量或方法'description' - I還會詢問信息的放置位置 - 是否進入類型表? – user1648020

+0

我應該在顏色模型中添加 - 'description'包含顏色名稱 – user1648020

+0

我認爲您需要使用:color_ids,:id,:description。這個:name只是'在模型上調用這個方法來給我選擇文本'。 – davidfurber

相關問題