Select Checkbox Pass Array in Ruby on Rails

How to get an array of values from a group of checkbox in Ruby on Rails?

Sometime digging the source code help us a lot, especially when the guide is not clear. Take a look at all check_box params

def check_box(object_name, method, options = {}, checked_value = "1", unchecked_value = "0")
Tags::CheckBox.new(object_name, method, self, checked_value, unchecked_value, options).
end

Here your form.check_box under a form_with of an object so the object_name is that object name call_up, method here is what object params you want to post player_ids, checked_value and unchecked_value are the values of that params when user submit the form, they will be send as an alternative checked/unchecked array of each checkbox [0, 1, 0, 1, ...], if you just want to send only checked values, just set unchecked_value = nil.

<td><%=form.check_box :player_ids, {multiple: true, skip_default_ids: false, class: "form-check-input"}, player.id, nil %></td>

One more thing, your controller will receive the has params object_name => {..., method: [...]}, so you need to permit that array:

def call_up_params
params.require(:call_up).permit(:name, player_ids: [])
end

Rails 3 select checkboxes - pass list to controller

As Legendary mentioned in the comments you need to wrap this in a form. A link_to isn't going to transmit the value of the selected ids unless its contained in its query parameters, which it can't know at render time.

Try something more like this:

<%= form_tag costprojects_viewprojects_path(format: "pdf") do %>
<% @costprojects.each do |costproject| %>
<tr>
<td><%= check_box_tag "costproject_ids[]", costproject.id %>
</td>
<% end %>
...
<%= submit_tag "PDF Selected", class: "btn btn-success" %>
<% end %>

You should then be able to access the array of cost_project_ids simply with params[:cost_project_ids] in the controller, which it seems you're already doing. Note that this will send an HTTP POST, rather than a GET, so ensure your routes are correctly setup for that verb.

Rails Checkboxes as array

If you save array in database add this to your model:

class Project < ActiveRecord::Base
serialize :topic
end

UPDATE

And make your form as:

 %p
= p.label "Value1"
= p.check_box(:topic, {:multiple => true}, "value1", nil, name:"project[topic][]")
= p.label "Value2"
= p.check_box(:topic, {:multiple => true}, "value2", nil, name:"project[topic][]")
= p.label "Value3"
= p.check_box(:topic, {:multiple => true}, "value3", nil, name:"project[topic][]")

and if you get permitted parameter issue add like:

params.permit! #only if you get issue of permitted parameter

Hope this will help you.

Rails - Pass multiple checkbox values through params

Since both smart_listing_controls_for and simple_form_for create a form, one problem you might have is that you are creating a form inside a form, and that is nor recommended nor standard. That might lead to unexpected results.

Maybe try doing it without the simple_form helper, something like this (assuming Certificate has a description attribute):

<%= smart_listing_controls_for(:search) do %>
<%= Certificate.all.each do |certificate| %>
<div class="checkbox">
<label class= "checkbox inline">
<%= check_box_tag 'search[certificates][]', certificate.id %>
<%= certificate.description %>
</label>
</div>
<% end %>
<% end %>

Update

Also, there's a problem with current release (v1.1.2) of the smart listing gem that doesn't allow to work with array inputs. Problem is in this part of the javascript code. This is fixed on current master branch and was updated recently on latest commit as you can see here.

To solve this use the latest commit in your Gemfile like this:

gem 'smart_listing', :git => 'https://github.com/Sology/smart_listing.git', :ref => '79adeba'

bundle install after updating Gemfile and try the above code again.

Return an array using `form_with`?

You should be able to do this like so:

<%= form_with model: @dog, local: true do |my_form| %>
<% ['labrador','husky'].each do |breed| %>
<%= my_form.check_box :breeds, {multiple: true}, breed%>
<%= my_form.label :breeds, breed.titleize %>
<%end%>
<%= my_form.submit 'Save' %>
<% end %>

The signature for check_box is (object_name, method, options = {}, checked_value = "1", unchecked_value = "0").

Since you are using the form builder the object_name can be omitted as it will be my_form.

So we pass:

  • the method :breeds,
  • the options {multiple: true} so that it creates a collection
  • the checked_value will be the breed name.

ActionView::Helpers::FormHelper#check_box Documentation

Rails: How to pass params of multiple checkbox to the model

I am a newbie with Rails. What I see is that you took the part of the form to create the team, right?

For your code straight forward it could be:

<%= form.label "Seleziona Categorie" %>
<% TeamCategory::NAMES.each do |name| %> #you are looping through team category NAMES constant
<%= check_box_tag 'category_names_selected[]', name %>
<% end %>

Your form as is allows more than one category to be selected.

For the method:

def create_tournament_team_categories(category_names_selected)
category_names_selected.each do |name|
team_category = name
self.tournament_team_categories << TournamentTeamCategory.create(team_category: team_category)
end
end

you will probably use this method in your teams_controller.rb. In the controller, you should be able to retrieve from params a freshly created array of selected names with something along the lines with this.

@category_names_selected = params[:category_names_selected]

I do not know how complicated your app is so it might also be nested under ["team"][:category_names_selected] or ["team"]["category_names_selected"] in your params hash.

To see the exact structure of the params hash and adjust the equation above you can add for example require 'pry' at the top of your controller file and then but the binding.pry just after the part where your method is executed. When you restart the server and the app hits this part of the controller you should be able to see the exact structure of your params hash in the terminal.

You can then pass the array to the method that you can call in the controller. Do not forget to add :category_names_selected to the strong params in the controller. I hope this helps.

Using checkboxes to submit values to an array

The code that ended up allowing everything to run properly is as follows. Ultimately, I believe the key difference was 'meat: []' in the controller.

Model:

class Order
include Mongoid::Document
field :type, type: String
field :meat, type: Array, default: []
field :cheese, type: Mongoid::Boolean

belongs_to :user
end

Controller:

def create
@order = Order.new(order_params)

if @order.save
redirect_to action: 'index'
flash[:notice] = "Successfully submitted order!"
else
render action: 'new'
end
end

private
def order_params
params.require(:order).permit(:type, :cheese, meat: [])
end

And view:

<%= form_for @order do |f| %>
<div>
<%= f.label :type %>:
<%= f.select :type, ['Burrito', 'Taco', 'Quesadilla', 'Salad Bowl'] %>
</div>

<div>
<%= f.label :meat %>
<%= check_box_tag 'order[meat][]', 'chicken', @order.meat.include?('chicken') %>
<%= check_box_tag 'order[meat][]', 'steak', @order.meat.include?('steak') %>
<%= check_box_tag 'order[meat][]', 'tofu', @order.meat.include?('tofu') %>
</div>

<div>
<%= f.label :cheese %>:
<%= f.check_box :cheese %>Yes
</div>

<div><%= f.submit %></div>

<% end %>

Hope this helps somebody.



Related Topics



Leave a reply



Submit