Rails,通过复选框发送模型ID数组

时间:2015-03-06 16:34:15

标签: ruby-on-rails ruby arrays ruby-on-rails-4 checkbox

我有三个表示模型的html表,每行都有复选框。

有一种模型与其他三种模型有has_and_belongs_to_many关联。我想通过复选框分配模型。我的想法是将选定模型的ID发送给控制器。

是否可以通过复选框发送到所选ID的控制器阵列并避免未选中的?因此,在控制器的行动中,我可以做类似的事情:

def action
   table1_ids = params['table1']
   table2_ids = params['table2']
   table3_ids = params['table3']

   table1_ids each do |id|
   #some action
   end

   table2_ids each do |id|
   #some action
   end

   table3_ids each do |id|
   #some action
   end
end

我的观点:

<%= form_for @player, {url: {:action => :add_details}, method: :post} do |f| %>

# some static html
<% @bases.each do |basis| %>
                <tr>

                  <td><%= **PLACE OF CHECKBOX** %></td>
                  <td><%= image_tag basis.image_url(:thumb), class: 'thumbnail' %></td>
                  <td><%= basis.name %></td>
                  <td><%= basis.short_info %></td>
                  <% end %>
                </tr>
            <% end %>

1 个答案:

答案 0 :(得分:0)

在你的参数中,你只会收到已检查项目的ID,因此控制器实际上执行了两个步骤。我有画廊,条目和照片,比如

Gallery
  has_many :entries
  has_many :photos, :through => :entries

并使用复选框为图库选择照片。更新时

@gallery = Gallery.find(params[:id])
photo_ids = params[:photo_ids]
photo_ids ||= []
@gallery.entries.each do |entry|
  photo_id = entry.photo_id.to_s
  if !photo_ids.include?(photo_id)
    # existing photo isn't selected anymore
    entry.delete
  else
    # photo is already selected, remove from selected list
    photo_ids.delete(photo_id)
  end
end
photo_ids.each do |photo_id|
  # make a new entry for additions to gallery
  entry = new Entry()
  entry.gallery_id = @gallery.id
  entry.photo_id = photo_id
  entry.save
end
相关问题