concating checkboxes in Ruby on Rails - ruby-on-rails

I have a field called delivery_day which is of type string in delivery_preference model.
In form, I want to provide 7 checkboxes for each day like Sunday,Monday,etc., and later want to concat.
For example if a user checks Sunday and Friday, I want to concat & store it as "Sunday,Friday" in delivery_day field.
Thanks in Advance!!

You can design your form like this -
<%= form_for #delivery_preference do |f|%>
<%= f.check_box :delivery_day, {multiple: true}, "Sunday" %>Sunday
<%= f.check_box :delivery_day, {multiple: true}, "Monday" %> Monday
<%= f.submit "Add" %>
<% end %>
After submitting the form, you can get your check box selections in your controller as follows:
def your_action_name
params[:delivery_preference][:delivery_day].delete("0")
DeliveryPreference.create(delivery_day: params[:delivery_preference][:delivery_day].join(","))
end
Hope it helps!

Might have better solutions, but when I encountered similar problem, I used check_box_tag to solve it.
<%= check_box_tag "delivery_preference[delivery_day][0]", 'monday' %>Monday
<%= check_box_tag "delivery_preference[delivery_day][1]", 'tuesday' %>Tuesday
<%= check_box_tag "delivery_preference[delivery_day][2]", 'wednesday' %>Wednesday
<%= check_box_tag "delivery_preference[delivery_day][3]", 'thursday' %>Thursday
<%= check_box_tag "delivery_preference[delivery_day][4]", 'friday' %>Friday
<%= check_box_tag "delivery_preference[delivery_day][5]", 'saturday' %>Saturday
<%= check_box_tag "delivery_preference[delivery_day][6]", 'sunday' %>Sunday
then you will receive an array like { deliver_day: ['monday', 'tuesday'] } in you controller. You can choose to concat in your controller, and then save, or you can move the logic to your model.
in your controller, you strong parameter should be like
params.require(:delivery_preference).permit(.., :deliver_day => [])
to permit the array.

I do not have enough reputation to leave a brief comment yet. However, does your migration have delivery_day have something similar to t.boolean :public, default: true_or_false_here within it?
If so, within the form, you could have something like:
...
<div class="form-group">
<%= f.label :public, class: 'checkbox' do %>
<%= f.check_box :public %> Monday
<% end %>
</div>
<div class="form-group">
<%= f.label :public, class: 'checkbox' do %>
<%= f.check_box :public %> Tuesday
<% end %>
</div>
...
After above, you could designate (via boolean logic) your "concat & store it as "Sunday,Friday"

Related

Retain checkbox value on page reload in form_with in Rails 5

I have a form created using form_with. What I need is to retain the values submitted using that form after page reload. I am able to save the value of text_field but not the value of check_box. What should I change in my code so that I can achieve the same?
html.erb
<%= form_with url: search_path,
id: :search_by_filter,
method: :get, local: true do |f| %>
<div>
<p><strong>Search by Name</strong></p>
<%= f.label 'Name' %>
<%= f.text_field :name, value: params[:name] %>
</div>
<br>
<div>
<%= label_tag do %>
<%= f.check_box :only_students, checked: params[:only_students] %>
Show only students
<% end %>
</div>
<br/>
<div class="submit_button">
<%= f.submit :Search %>
</div>
<% end %>
controller.rb
def get_desired_people(params)
people = Person.includes(:country, :state, :university).order(id: :desc)
people = people.where(is_student: params[:only_students]) if params[:only_students]
people = people.where(name: params[:name]) if params[:name].present?
people
end
Here I am able to retain the value of params[:name] but not the value of params[:only_students]. It always remains unchecked after form submission. How can I retain the checked and unchecked value?
f.check_box check_box_tag is expecting checked to by boolean value, and every param is a string (string is always evaluated to true if exists) so you should do:
checked: params[:only_students].present?
you don't have to worry about a value of param, as unchecked params are not send while posting.
EDIT:
above works for check_box_tag.
f.check_box is tricky, you should carefully read description: https://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html#method-i-check_box
The behaviour you described seems pretty correct, you can deal with it or switch to check_box_tag as a better option when not updating model attributes
All the solutions above did not work for me. Try this:
<%= check_box_tag :only_students, true, params[:only_students] %>

Serialized fields_for not populating from db on edit

On the edit page for this form all of the fields outside of the fields_for tag (inbox name, automatic reconciliation, and a few others not listed here) are all populating based on their corresponding db value. However, everything inside the fields_for tag are not, even though they're posting to the db just fine.
I posted :group_member_roles as an example but there are a few other fields inside their own other fields_for that are doing the same thing. It's just confusing that it will post to the db but not display on edit.
The more I read into fields_for the more I feel like I'm not using it correctly. It seems to be more inclined to populating db tables outside of the one your form is currently referencing, but I'm just trying to serialize data within the inbox table. When I look at the :group_member_roles column I want it to be an array/hash containing process true/false, action add/delete, and a string of values.
#_form.html.erb
<%= form_for(#inbox) do |f| %>
<%= f.label :inbox_name %>
<%= f.text_field :name, placeholder: "Inbox Name" %>
<%= f.label :automatic_reconciliation, "Turn on/off automatic reconciliation" %>
<div class="switch small">
<%= f.check_box :automatic_reconciliation, class: "switch-input" %>
<label class="switch-paddle" for="inbox_automatic_reconciliation">
<span class="show-for-sr">Automatic reconciliation</span>
<span class="switch-active" aria-hidden="true">On</span>
<span class="switch-inactive" aria-hidden="true">Off</span>
</label>
</div>
<%= f.fields_for :group_member_roles do |group_member_roles| %>
<h4>Group Member Roles</h4>
<%= group_member_roles.label :process, "Turn On/Off Processing" %>
<div class="switch small">
<%= group_member_roles.check_box :process, class: "switch-input" %>
<label class="switch-paddle" for="inbox_group_member_roles_process">
<span class="show-for-sr">Group Member Roles Processing</span>
<span class="switch-active" aria-hidden="true">On</span>
<span class="switch-inactive" aria-hidden="true">Off</span>
</label>
</div>
<%= group_member_roles.label :action, class: "hide" %>
<%= group_member_roles.select :action, ["Add", "Delete"], { selected: "Add" }, { class: "hide" } %>
<%= group_member_roles.label :values %>
<%= group_member_roles.text_field :values, placeholder: "1234, 1337, 1986" %>
<% end %>
Thanks in advance for any help or guidance.
The fields were being stored as a hash and the field was looking for an object to populate with so I added an OpenStruct dummy object to the fields_for to make it so. If anyone can think of a better way please let me know as this is pretty ugly code.
<%= f.fields_for :group_member_roles, OpenStruct.new(f.object.group_member_roles) do |group_member_roles| %>

How to use checkbox in ruby on rails

I have a code of checkbox below in ruby on rails:
<%= check_box(:Monday,{:id => "Monday",:value => "Monday"}) %>
But, it shows only the checkbox but not shows its text i.e "Monday".
So what should I do to display the text of checkbox, kindly suggest me, waiting for reply. Thanks
Have you read this?
http://apidock.com/rails/v4.0.2/ActionView/Helpers/FormTagHelper/check_box_tag
Either you use the check_box_tag or the f.check_box inside a form builder, plus you have to add a label to display it.
The construct you are using just generate the <input type="checkbox" value="something" /> and not the label, that you have to add, just like text or with a <%= label_tag 'whatever' %>.
try the below code
<%= check_box :monday, {:class => "anyclass", :style => "anystyle"}, "monday" %>
one way to do is
<%= check_box_tag "Monday", 'yes', id:"monday" %> Monday
or u can do this also
<%= check_box_tag "Monday", "yes" %>
<%= label_tag "Monday" %>
You need to use a label:
<%= form_tag your_path do %>
<%= label "Day" %>
<%= check_box "Monday", "yes" %>
<% end %>

Ruby on rails drop down box Beginner lvl

So I am a beginner in ROR, like I know it for a month (school assignment and we don't get a cursus we need to use 'google')
So I want a dropdown box with a list of all my cities. Then if I pick a city I need to save the city_id in my database together with the date. The code I have so far seem to work except when I click on save it says that city is empty (and it can't be empty because of the failsave)
this is my code
<div class="field">
<%= f.label :stad_id %><br />
<% cities_array = Stad.all.map { |stad| [stad.naam, stad.land] } %>
<%= select_tag(Stad, options_for_select(cities_array)) %>
</div>
<div class="field">
<%= f.label :datum %><br />
<% datum = Time.now.to_s(:db) %>
<%= f.text_field :datum, :value => datum.inspect, :readonly => true %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
I don't really know what I am doing wrong except I have an eery feeling I don't actually give the command to save it.
help is much thanked
sincerely
Robin
There are a few things I notice here that are wrong.
1) Put the creation of the cities_array into your controller, not in your view:
def edit
#something = Something.find(params[:id])
#cities_array = ... whatever ...
end
2) When creating your cities_array, you need to specify the ID of the city as the second parameter, like this:
#cities_array = Stad.all.map { |stad| [stad.naam, stad.id] }
3) The select_tag call isn't for Stad, it's for the model you're trying to save. For example, your form might look like this:
<%= form_for #something %>
<%= f.label :city %>
<%= f.select :city_id, #cities_array %>
# or!
<%= select :something, :city_id, #cities_array %>
<% end %>
I hoep this clears things up for you.

Rails metasearch search_form with checkboxes

I am a little confused.
Despite all questions around this theme here, I can't find the right solution.
What I want to do is to simply add check-boxes to my index filter form.
I am using Metasearch gem and here is my current code :
<form class="filter_form">
<%= form_for #search do |f| %>
<%= f.collection_select :categories_id_equals, Category.all, :id, :name, :include_blank => true, :prompt => "All categories" %>
<%= f.collection_select :location_id_equals, Location.all, :id, :name, :include_blank => true, :prompt => "All locations" %>
<ul>
<b> Type </b>
<% Type.all.each do |type|%>
<li>
<%= check_box_tag :types_id_equals, type.id %>
<%=h type.name %>
</li>
<% end %>
</ul>
<%= submit_tag "Find Now", :class => "find" %>
<% end %>
All works fine, except the checkboxes.
I don't have much experience in rails, so I don't really see what I am doing wrong and what could be the most convenient and simplest way.
Update
.....................
More explanation - I have a model Trips, which has HABTM relationship with two models (
Categories, Types) and belongs to Location.
I want to be able to filter Trips on it's index by categories (f.collection select) ,location (f.collection select) and types (checkboxes).
After checking types and submitting - nothing changes, no filtering is done!
<%= check_box_tag "type_ids[]", type.id %>
Will do it for you. The selected ids will be transfered as a string seperated by commatas. You can find them in params[:type_ids] but you have to deal with them manually! Rails is not a magican, its a framework.
Here's how I handled it.
<% #sub_categories.each do |cat| %>
<h2><%= cat.name %> <%= check_box_tag "q[product_category_id_in][]", cat.id %></h2>
<% end %>
Basically just q is whatever your query param is, then right after that in brackets sub in your meta_search method. I used whatever_foreign_key_in since I want to be able to add more than one id to the array to search on. Then add empty brackets after it so rails handles the post params correctly.

Resources