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.
Related
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.
I have another form_for select question.
I'm using a partial for my new and edit form for my Customer model. The :customer_type can be one of three values: Contractor, Business, Homeowner. So, I put these values in an array in my model.
def self.customer_types
customer_types = ['Contractor', 'Homeowner', 'Business']
end
In my form I do this:
<%= f.select(:customer_type, options_for_select(Customer.customer_types)) %>
This works fine in the new form, but on the edit form, how do I get the selected value for :customer_type to be selected? I've tried several things but nothing works for me.
Thanks for any tips.
-jc
options_for_select takes an optional second argument, which is the selected option :)
http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-options_for_select
The second thing you need is the actual value, which can be accessed via f.object. So something along those lines
<%= f.select(:customer_type, options_for_select(Customer.customer_types, f.object.customer_type)) %>
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.
In an existing codebase, one attribute of the discount model is discount_type. Since there are only 2 types of discounts (percentage and cash) used in this system, they are hardcoded as percentage or cash throughout the system, there is no discount_types table or anything to map to.
In the form, there is the following code:
=form_for #discount do |f|
...
=f.select :discount_type, options_for_select(["percentage", "cash"])
...
This works great for new discounts, but when pulling up the form to edit a discount, percentage is always selected, no matter what the discount object's discount_type is. How do we get the form to default to the discount_type of the object being edited?
Wouldn't simple
= f.select :discount_type, ["percentage", "cash"]
be enough?
I would like to know which way is the best to resolve my question :
I have a form in order to select people via a select field. If the name is missing in the select field, a text field is available to add directly the person's name.
- The form in new.html.erb is the format of the new action of the Team controller.
- The list of the people is extracted from the People model.
def new
#team = Team.new
#people = People.all
end
I created an attribute in the Team model to store the new_person text field :
class Team < ActiveRecord::Base
attr_accessor :new_person
...
end
Finally, here's an extract of my view :
<%= f.select :person_id, #people.map { |p| [p.name, p.id] } %>
<%= f.text_field :new_person %>
Obviously, I would like to save the new person in the table Person before saving the data from the form. As usual, the id are saved instead of the names
At this point, I've got two issues :
1/ The params array has the key new_person what doesn't have the table. So it is not possible to use the Team.new(params[:team]) method. Does exist an easy solution to avoid this problem ?
2/ As I need the person_id, how can I get it when the name comes from the new_person field? In using the before_filter method ?
Thanks a lot,
Camille.
1) You should consider using fields_for in your view within your form_for block. This will allow you to specify that the fields within the fields_for block are attributes of a different model, will generate the appropriately named input fields, and allow you to use params[:team] in your controller. See the FormHelper documentation for more on this.
2) While you could do something in your controller to first check for a value in the new_person field, create the record, update the contents of params[:team] with the value of the newly created person and create the team, this feels a bit like a hack to me. Another possible solution which may be less fragile would be to use some JavaScript on the page that would render some kind of modal dialog for the user to create the new person, submit the new person to the person#create controller method, then refresh your drop down. It would probably not be terribly difficult to do this using a jQuery UI modal form (very good example at that link to do what you need) with Rails remote form and unobtrusive JavaScript.
This is probably a more difficult solution to your second question than you are hoping for, but probably more useful in the long run.