Checkbox is set for each content post Since Ajax is not used, XML communication is turned off with the form_with option.
ruby:index.html.erb
<%= form_with model: @contents, url: contents_path, method: :delete, local: true do |f| %>
#local:Turn off XML communication with true
<% @contents.each do |content| %>
<% @count += 1%>
<td>
<%= f.check_box :content_ids, {type: 'checkbox', class: 'checkbox-select', id: "checkbox#{@count}", multiple: true}, content.id %>
<%= f.label :'', for: "checkbox#{@count}",class: 'select-label' %>
</td>
<% end %>
<% end %>
This will add a checkbox for each post
I tried to summarize only the necessary options of form_with according to the purpose of this time
python
<%= f.check_box :content_ids, {type: 'checkbox' multiple: true}, content.id %>
multiple: Add true to allow multiple values to be sent to the controller as an array.
A hash called contents is sent to the controller. key is contents_ids, value is an array. And the content.id is in the array
Value sent from view
"content"=>{"content_ids"=>["1", "2"]}}
It's complicated (laughs)
First, get the value sent from View with the strong parameter
contents_controller.rb
def select_content_params
ids = params.require(:content).permit(content_ids: [])
ids.values[0]
end
1st line: Only content_ids in the sent content can be used, and if unexpected data is sent, it will be ignored. 2nd line: Extract only the array using the values method for ids. Since the value at this time is [["1", "2"]], specify [0] and extract only ["1", "2"].
After that, write the process using the formatted value
contents_controller.rb
def select_destroy
if select_content_params.uniq.count == 1
redirect_to contents_url, notice: "Please select the item to delete"
else
select = []
select_content_params.map{|n|
select << n
select.delete("0")
}
select.each{|id|
content = Content.find(id)
content.destroy
}
redirect_to contents_url, notice: "I deleted the bookmark"
end
end
Strictly speaking, values that are not checked in the check box are sent as 0, so the uniq method is used to eliminate duplication, and the count method is used to count the number of array values and if branch. Not checked → Only 0 == 1 Checked → 0 and id exist> 1
If it is not checked, it may be easier to return nil, but please do as you like.
routes.rb
delete "contents" => "contents#select_destroy", as: 'select_destroy'
Completed with!
Thank you for your cooperation. If you have any questions, I would be grateful if you could ask for a professor!
Recommended Posts