Rails: Need Multi Select Form To Submit Data in Se

2019-08-31 06:27发布

I currently have the below working properly in my application:

Form

<%= 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 %>

Controller

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

Type Model

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

Task Model

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

My problem is that when submitted the information all goes into the same row and 'name" field in the types table -- I need it to create separate rows in the types table.

I need this solution http://forums.phpfreaks.com/topic/195729-multiple-select-drop-down-data-saved-to-mysql-how/ but for Rails

I can get separate rows created using text fields with the below code:

Form

<%= 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 %>

Controller

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

Any assistance wold be appreciated.

1条回答
别忘想泡老子
2楼-- · 2019-08-31 06:55

Here is an example from a project of mine:

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}

Here is the HTML of the above collection_select:

<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>
查看更多
登录 后发表回答