How to show text instead of integers? - ruby-on-rails

I have a form with a pull down list of Races (asian, caucasian, African/black, etc).
These races are represented by my Race model. I can create a record successfully, however, when I try to view the record the corresponding integer of the race is displayed and not the text.
How do I get the text associated instead of the integer id?
Thanks.

Provided you supply a minimum set of data for us to assist, I risk an answer as generically as I can.
If you are using a form_for builder
<%= f.collection_select :race_id, Race.all, :id, :name %>
or whatever you call your fields
If you are using a form_tag
<%= select_tag :race_id, options_from_collection_for_select(Race.all, "id", "name") %>
These are as I said pretty generic answers, you can build further on them. Check this link for more:
http://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html

You are seeing the value of the selected option which is the index of the array I imagine. You can use that index to get the text value from your races array. Without seeing more code that is all I can provide.

Related

Issue with Rails multi select options field

I've set in my model('Bambino') a multi-select field to assign a value to the string attribute 'status'. Find the code below from my form partial:
<%= f.select(:status, options_for_select([['segnalato','segnalato'],
['inserito','inserito'],['drop','drop'],['concluso','concluso']])) %>
When I want to edit my record the edit form does not give me back the previous stored value but sets automatically the default value to 'segnalato' (E.g.:if I create a new record setting the status to 'inserito' and after I want to edit the record I get the edit form with the default value of 'segnalato' while I am expecting to see in the field 'inserito').
In this way when you edit a record chances to make a data entry mistake are very high. Why so? Is there a way to retrieve the proper 'status' value that was assigned when the record was created? Thanks
Are you sure that #your_record.status is equal to one of those values? Check it out before any further debugging.
Whilst Andrey Deineko's answer is probably the one you want, there is a better way to achieve what you're doing: enum.
#app/models/bambino.rb
class Bambino < ActiveRecord::Base
enum status: ['segnalato', 'inserito', 'drop', 'concluso']
end
This will give you the ability to use the following:
<%= f.select :color, Banbino.status.to_a.map { |w| [w.humanize, w] } %>
This will store a number for the status, whilst allowing you to define what each number means. It won't do anything about loading a pre-selected object (that's what Andrey's answer will do), but will give you the ability to make your application & select more succinct.

How to convert cents to dollars for all drop down values in Rails

I am having a field named price_in_cents for materials table.
I want to display all the values of price_in_cents as dollars in drop down.
Here is the code:
<%= select_tag 'price_in_cents', "<option value='blank'>(empty)</option>"+options_for_select(Material.pluck(:price_in_cents).compact.uniq),include_blank: true, class: 'form-control' %>
Actually price_in_dollars = self.price_in_cents/(100*100).to_d
For example price 10200 has to be displayed as 1.02.
How to write or mention the values as price_in_cents/(100*100).to_d in drop down?
You can try like this:
<%= select_tag 'price_in_cents', "<option value='blank'>(empty)</option>"+options_for_select(Material.pluck('price_in_cents/(100*100)').compact.uniq),include_blank: true, class: 'form-control' %>
Here, performing operation while fetching record value. If you want to convert it into integer then you can write it as:
Material.pluck('CAST(price_in_cents/(100.0*100.0) as decimal)').compact.uniq
I have given example of postgresql
You probably want to keep this conversion logic out of your views-- this sounds like a situation where the Decorator Pattern would be appropriate and would recommend looking into a gem like Draper. You could add a price_in_dollars method to your MaterialsDecorator and use a decorated #materials in your view.
Or if you are strictly looking for an array of these values, a class method such as Material.prices_in_dollars might be appropriate.
If you are dealing with money, I suggest you use something like money-rails, it will add the necessary readers and writers for you to access the money value in dollars and save you some rounding headaches.

Hidden_field tag grabbing an id from a form select

I have the following code where I want to take the selected photo (from a drop-down) and pass it into a hidden_field. The collection select is a group of photos and I am using the same variable #photos within the hidden_field.
<%= f.select :photo_id, options_from_collection_for_select(#photos, :id, :name), {include_blank: "- Select A Photo-"} %>
<%= f.hidden_field(:photo_id, value: #photos.id)%>
I realize that using the variable that holds all the photos in the hidden field is incorrect because I don't want to all the photo's id's... but how might I get that one selected photo id?
I tried looking at some Rails sources and started running circles as I quickly confused myself... If you happen to know of a good source for this I would greatly appreciate a link as well.
Forms are like hashes in that they can only have one value per key. So if you have two input fields that both have a name="photo[photo_id]" then the latter one will prevail.
I think what you want to do is have the hidden_field be the carrier of the value, but the select field be the chooser of the value. I can't think of a way to do this except with javascript.
<%= f.select_tag :photo_id...
<%= f.hidden_field :photo_id, value: current_selected_photo.id...
And then in javascript (coffeescript):
$ ->
$('select[name="photo_id"]').on 'change', ->
$('input[name="photo[photo_id]"').val($(#).val())

Accessing form values for use in hidden fields using Ruby on Rails

I have three select tags for birthday (day/month/year) that look like this one:
<td><%= select_tag(:birth_day, options_for_select((1..31)), {:id => 'select1'}) %></td>
I'm trying to access the three values and combine them into a single string and then submit that string using a hidden field. I can't figure out how to get the values to read them into the hidden field.
Right now my best attempt is:
<%= f.hidden_field :combined_date, :value => "#{#birth_day}" %>
But birth_day just comes through as an empty string. (I'm planning on combining this string with birth_month and birth_year after I get the values to read in).
Can someone please help me with this problem?
Why not just combine them when you save the record?
In controller:
combined_date: (params[:day]+"/"+params[:month]+"/"+params[:year]).to_date
#record.save
It's not elegant, but at least you don't need to use javascript just to unnecessarily combine them on the client side.

How to convert an integer column in the model to be used as a string in the view

For database columns that are integers that "represent" strings, what is the best way to show the string value in the view?
For example, if I collect "payment_method" values as integers in my form as follows:
<%= f.select :payment_method, { "Visa" => "1", "Mastercard" => "2", "Amex" => "3"} %>
How can I show the saved integer as a string in my view files? What can I add to my model, so that
<%= #relevantvariable.payment_method %>
or something similar returns string values like "Visa", "Mastercard" or "Amex" instead of their respective integer values?
Thanks much for handling such a basic question!
Either don't use an integer value, and store the payment method directly as a string in the db, or create a PaymentMethod model.
With the association set up, you'd be able to refer to the name of the payment method as so:
<%= #relevantvariable.payment_method.name %>
Don't try to manually handle lists of names / ids - that will quickly get unmanageable.
Edit: after reading your comment, if you went with the first option and stored a string in the table, definitely don't allow the user to type the value directly, maintain a list on the model (or similar), that you seed your dropdown from, that way you're still constraining the possible values. You could even add a custom validator if you want to be certain what you putting in the database.
I'd stick with cheeseweasel solution but you can do one thing to show that on your view...
<% if #relevantvariable.payment_method == 1 %>
<%= "Visa" %>
<% else %>
<%= "Mastercard" %>
You probably would want to use a switch/case instead but you got the idea
As I said I think you should stick with cheeseweasel solution since there are many problems with this approach... it's your call
So you have your payment methods in a separate table payment_methods and the owner ( say user) contains a has_one relationship with it
class User < AR::Base
has_one :payment_method
end
Then show the payment method name just like
<%=
#user.payment_method.name #or whatever you have.
%>
However, while you are loading the #user data, you can perform a eager loading by :include. Like
User.find(user_id, :include => :payment_method)
This will load the PaymentMethod data earlier even for multiple users with single query.

Resources