Reputation: 47
Hello Im working on a rails project. Its a project that selects a list of contacts from the phonebook(index view) and sends texts to only the selected. So I would like to introduce a checkbox on the index view that selects a few of the contacts and sends this data to my controller. Any help on how I can go about this?
Upvotes: 1
Views: 91
Reputation: 141
Use multiple
option for check_box.
f.check_box :checked, {multiple: true}, value, nil
By using the multiple option, parameter can have array values. You can put the default value in the fourth argument, but nil is good as long as you don't need any particular action.
This check_box tag can be called many times, only the checked value can be obtained with params.
checked_values = params[:checked]
Perhaps in your case, set contact ID to the checkbox value, fetch records from model based on this ID, and implement the following processing.
Edit:
In response to comment, here is an example.
How do I display all of them including the checkbox in my index view?
According to the design pattern, index action would have a list of contacts. I don't comprehend your project, but I assume the project has Contact
model.
def index
@contacts = Contact.limit(20)
end
Then, render index view with @contacts
and check_box.
<%= form_for :contacts, url: {action: :send}, html: {method: :post} do |f| %>
<% @contacts.each do |contact| %>
<div>
<%= f.check_box :checked, {multiple: true}, contact.id, nil %>
<%= "name: #{contact.name}, phonenumber: #{contact.phonenumber}" %>
</div>
<% end %>
<%= f.submit 'Submit' %>
<% end %>
Since this form is assumed to send data to send
action, send
would be implemented as follows.
def send
# fetch checked id and find record from model
checked_ids = params[:contacts][:checked]
contacts = Contact.where(id: checked_ids)
# add your code
end
Of course this is just an example, please refer this and implement for your own project.
Upvotes: 1