【问题标题】:Rails, send arrays of model IDs via checkboxesRails,通过复选框发送模型 ID 数组
【发布时间】:2015-03-06 16:34:14
【问题描述】:

我有三个代表模型的 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 %>

【问题讨论】:

  • 需要更多信息。请展示你的观点,并解释一下你想要完成的事情
  • 我添加了更多信息

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


【解决方案1】:

在您的参数中,您将只收到检查项目的 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

【讨论】:

  • 我需要在我的 html.erb 的 &lt;%= **PLACE OF CHECKBOX** %&gt; 位置写些什么?
猜你喜欢
  • 1970-01-01
  • 2013-12-04
  • 2021-06-01
  • 1970-01-01
  • 2014-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-25
相关资源
最近更新 更多