Text fields from array in Rails - ruby-on-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']

Related

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

How to submit an array of integers in a Rails form?

I would like to know if there is a way to have some sort of input field in a Rails form, so that if the user enters 1, 2, 3, then params[:model][:attribute] returns [1, 2, 3] or at least ['1', '2', '3'], but not ['1, 2, 3'].
Background:
I have a model Foo, which has an attribute bar_ids. The datatype of this attribute in the PostgresQL database is Array. I've tried several things:
if f.text_field :bar_ids then params[:foo][:bar_ids] returns '1, 2, 3'
if f.text_field_tag 'foo[bar_ids][]' then params[:foo][:bar_ids] returns ['1, 2, 3']
if f.number_field :bar_ids then params[:foo][:bar_ids] returns '1' if I input only 1 and the form does not allow to input multiple numbers
So, again my question - is there a way to construct my form in such a way, so that Rails automatically parses the input to the respective datatype, in my case - an array of integers?
People usually edit the params manually before updating the model:
params[:model][:attribute] = params[:model:][:attribute].split(',')
# ...
Model.update_attributes(params[:model])
It is usually done in controller action or in before_action.

Array as Parameter from Rails Select Helper

I'm working on a legacy project that is using acts_as_taggable_on which expects tags to come in arrays. I have a select box allowing users to select a tag on a Course in a field called categories. The only way mass assignment create will work is if params looks like this params = {:course => {:categories => ['Presentation']}}. I've currently a view with this helper:
<%= f.select 'categories', ['Presentation' , 'Round Table' , 'Demo', 'Hands-on'] %>
Which will give me a parameter like params = {:course => {:categories => 'Presentation'}}. This doesn't work since Acts as tag gable apparently can't handle being passed anything other than a collection.
I've tried changing categories to categories[] but then I get this error:
undefined method `categories[]' for #<Course:0x007f9d95c5b810>
Does anyone know the correct way to format my select tag to return an array to the controller? I'm using Rails 3.2.3
I didn't work with acts_as_taggable_on, but maybe this simple hack will be suitable for you? You should put it before mass-assignment.
category = params[:course][:categories]
params[:course][:categories] = [category]
If you are only going to allow the selection of ONE tag, you could do:
<%= f.select 'categories', [['Presentation'] , ['Round Table'] , ['Demo'], ['Hands-on']] %>
Each one item array will have first for the display value, and last for the return value, which in this case will both return the same thing, as the first element of the array is the same as the last element when the array as one element.
Seems like select doesn't give you that option.
If I understand correctly, one option might be to use a select_tag instead and just be explicit about where you want the selection in the params:
<%= select_tag 'course[categories][]', options_for_select(['Presentation' , 'Round Table' , 'Demo', 'Hands-on']) %>
That ought to get your params the way you need them.
Here's what I'm using for one of my projects:
<% options = { include_blank: true } %>
<% html_options = { required: true, name: "#{f.object_name}[#{resource.id}][days][]" } %>
<%= f.select :days, DAYS, options, html_options %>
Without html_options[:name], Rails handles the name of the select tag and spits out something like
service[service_add_ons_attributes][11][days]
but I need
service[service_add_ons_attributes][11][days][]
So I override it.
Hope that helps.

How to display Rails select field values rather than stored integers in other views

I'm using a select field in a Rails app that is NOT tied to a related model, but stores integer values for a static series of options , i.e.,
<%= select (:this_model, :this_field, [['Option1',1],['Option2',2],['Option3',3],['Option4',4]] ) %>
In a show/ index view, if I want to display the option text (i.e. Option1, Option2, etc) rather than the integer value stored in the database, how do I achieve this?
Thanks for helping a noob learn the ropes!
EDIT
Based on Thorsten's suggestion below, I implemented the following. But it is returning nil, and I can't figure out why.
Invoice model:
##payment_status_data = { 1 => "Pending Invoice" , 2 => "Invoiced" , 3 => "Deposit Received", 4 => "Paid in Full"}
def text_for_payment_status
##payment_status_data[payment_status]
end
Invoice show view:
Payment Status: <%= #invoice.text_for_payment_status %>
In the console:
irb > i=Invoice.find(4)
=> [#<Invoice id: 4, payment_status: 1 >]
irb > i.text_for_payment_status
=> nil
I've tried defining the hash with and without quotes around the keys. What am I missing?
something like this would work:
<%= form_for #my_model_object do |form| %>
<%= form.label :column_name "Some Description" %>
<%= form.select :field_that_stores_id, options_for_select({"text1" => "key1", "text 2" => "key2"}) %>
<% end %>
Update
If you later want to display the text you can get it from a simple hash like this:
{"key1" => "text 1", "key2" => "text2"}[#my_object.field_that_stores_id]
But you better store this hash somewhere in a central place like the model.
class MyModel < ActiveRecord
##my_select_something_data = {"key1" => "text 1", "key2" => "text2"}
def text_for_something_selectable
##my_select_something_data[field_that_stores_id]
end
end
Then you can use it in your views like
#my_object.text_for_something_selectable
There are many possible variations of this. But this should work and you would have all information in a central place.
Update
Ok, I used something similar for our website. We need to store return_headers for rma. Those need to store a return reason as a code. Those codes are defined in an external MS SQL Server Database (with which the website exchanges lots of data, like orders, products, and much more). In the external db table are much more return reasons stored than I actually need, so I just took out a few of them. Still must make sure, the codes are correct.
So here goes he model:
class ReturnHeader < AciveRecord::Base
##return_reason_keys = {"010" => "Wrong Produc",
"DAM" => "Damaged",
"AMT" => "Wrong Amount"}
def self.return_reason_select
##return_reason_keys.invert
end
def return_reason
##return_reason_keys[nav_return_reason_code]
end
end
Model contains more code of course, but that's the part that matters. Relevant here is, that keys in the hash are strings, not symbols.
In the views i use it like this:
In the form for edit:
<%= form_for #return_header do |form| %>
<%= form.label :nav_return_reason_code "Return Reason" %>
<%= form.select :nav_return_reason_code, options_for_select(ReturnHeader.return_reason_select, #return_header.nav_return_reason_code) %>
<% end %>
(Maybe no the most elegant way to do it, but works. Don't know, why options_for_select expects a hash to be "text" => "key", but that's the reason, why above class level method returns the hash inverted.)
In my index action the return reason is listed in one of the columns. There I can get the value simply by
#return_headers.each do |rh|
rh.return_reason
end
If you have trouble to get it run, check that keys a correct type and value. Maybe add some debug info with logger.info in the methods to see what actual data is used there.

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