saving collection to database using simple_form in rails - ruby-on-rails

I am using simple form to make checkboxes as below:
module ApplicationHelper
def all_colors
t = [
"A",
"B",
"C",
"D"
]
return t
end
<%= f.input :colors, :label=>false, :collection => all_colors, :as => :check_boxes%>
When the user selects some checkboxes and submits the form, the data saved in databases also has non selected items empty location.
For example If user checkmarked B and D then data saved in DB will look like:
---
- ""
- B
- ""
- D
I want the data to be saved as CSV

At a glance it seems to me you might be passing extra commas in your input so when your user checkmarked B and D what got passed back in the request was- ,B,D,.
When you parse the input to save the extra commas were translated into empty values.
Check the request variables that were posted back by the form submit and strip away the extra commas.

Related

options_from_collection_for_select selected value on form reload

I am a novice in RoR.
I have this line in the code along with other select objects.
<%= f.select :from_branch, options_from_collection_for_select(#branches, :id, :name, #form.from_branch), {}, :disabled => params[:repoid].blank? %>
In the webpage, when there is an error in any input, the form reloads and keeps the previously entered values intact. But for the above select tag, it resets it to the first entry. There are no blanks in the collection.
Say there are three values in the collection - A, B, C. A is the first record and selected. I select C and submit the form. Due to an error in the form it reloads. Now I want this field to have C. Instead it again goes back to A.
Any thoughts on how do I achieve this?

Rails 4.2: display postgres array value in view form

There is a string array segment defined in psql. Here is the db migrate file:
t.string :segment, array: true, default: []
When a value for segment is entered, the value is put within {} and is saved into the psql correctly. Here is a value in postgres:
{#6CF511,#EDF511,#F51111}
But when this value is displayed in view with the code below:
<%= f.input :segment, :label => ('Seg Range Color Choices')' %>
But the value displayed is not correct:
["#6CF511", "#EDF511", "#F51111"]
Every value is appended " before and after. Also the [] instead of {} is used. The following jquery code is used to filled out the value:
$('#dashboard_detail_segment').val("<%=rpt_detail.segment%>");
In debug, rpt_detail.segment = array[3]. rpt_detail.segment.join(',') can be used to turn the array into a string of "#6CF511, #EDF511, #F511112" and this may be one way to display. My question is that is there other natural way to display the segment in Rails view?
Use the raw method so that Rails will not html escape the output.
$('#dashboard_detail_segment').val("<%= raw rpt_detail.segment %>");

How to add multiple single-name elements in one form with Rails?

I have three models that need to work together - product, line_product and order, where line_product mirrors product for order. So that it looks like so:
product.rb
has_many :line_products
order.rb
has_many :line_products
line_product.rb
belongs_to :order
belongs_to :product
And I'd like to make a form where there's a list of products with an input field next to each and a user can input any number (count) for any product, click submit and all the products with a count more than 0 in their form, will become line_products for order where order.id: 1 (for example). As of now only the last product gets added to the order.
How could I do this?
Edit
The form looks like so:
= form_for #line_product do |lp|
= lp.hidden_field :order_id, value: Order.last.id
%section#product_list
- if notice
%section.notice=notice
%ul#products
-#products.each do |p|
%li.product_list
%article.product
%section.product_left
= image_tag p.image.url(:medium)
%div.clear
%span.price= number_to_currency(p.price,:unit=>'€ ')
%section.product_right
%section.product_about
%span.title= p.title
%span.description= p.description
%span.description.desceng= p.description_eng
= lp.hidden_field :product_id, value: p.id
%section.product_order
= lp.number_field(:count, min: '0', value: '', class: 'product_count')
%section#order_accepting
= lp.submit "Add to cart", class:'add_to_cart'
You're hitting expected behavior. This is actually how rails forms handle checkboxes that are unchecked. This actually more of an HTTP form post question, generating the HTML with rails / haml isn't the issue.
Use an array form POST an array from an HTML form without javascript
There are quite a few ways you could handle this, for example you could go down the route of using accepts_nested_attributes which is a fairly generic way of generating forms that create/edit multiple objects and then handling that data.
A slightly simpler alternative for this particular case would be to generate a single number input for each product (rather than the pair of hidden input and number input you have)
number_field_tag "count[#{product.id}]"
This will result in params[:count] being a hash of the form
{ "1" => 23, "2" => "", "3"=> "1"}
Assuming that you had 3 products with ids 1,2,3 and that you had entered 23 for the first quantity and 1 for the last.
You would then need some controller code to iterate over this hash and build the corresponding line_product objects

Text fields from array in Rails

I'm trying to generate a set of text fields for an array using Rails 2.3. I have an array in my controller (which is not part of the model), and I'd like to make a text field for each entry. The array is like:
#ages = [1, 3, 7] # defaults
Then, I'd like to generate 3 text field in my view with the values 1, 3, and 7, and have the array filled with the user's values when submitted.
I found a bunch of stuff on Google and here, but none that seemed to work for me. I'm sure this is easy in Rails...
Rails can serialize collections, which should make this easier.
If you name your inputs like 'field[]' like this in your view:
<% #ages.each do |age| %>
<%= text_field_tag 'ages[]', age %>
<% end %>
Then you can access all 'ages' in your controller on submission:
#ages = params[:ages] # ['1', '3', '7']

rails bringing back all checkboxes instead of only selected one

I am using simple_form and have a following sample tag:
<%= f.input :medical_conditions, :label=>false, :collection => medical_conditons, :as => :check_boxes%>
The collection holds about 100 checkboxes. However, when user only selects 1 or 2, everything is still getting saved to the database like this:
---
- ""
- ""
- ""
medical_conditions is a simple array in my application_helper
def medical_conditons
t = [
"Allergies/Hay Fever",
"Diabetes",
"Heart Surgery"]
return t
end
the medical_conditions field is a :string field.
What do I need to do so that only values that are selected are saved in comma separated manner.
It is not simple_form behavior. It is from Rails. See this: http://d.pr/6O2S
Try something like this in your controller (guessing at how you wrote your create/update methods)...
params[:medical_conditions].delete('') #this will remove the empty strings
#instance.update_attribute(:medical_conditions, params[:medical_conditions].join(','))
#or however you want to save the input, but the key is the .join(',') which will
#create a comma-separated string of only the selected values, which is exactly
#what you're looking for me thinks :-)
If that does the trick for you, I'd consider making a private helper method that formats the params for you so that you can use it in #create, #update, or wherever else you need it. This should keep things a little cleaner and more "rails way-ish" in your crud actions.

Resources