Rails - map form values to database - ruby-on-rails

How can I set up my Model so fields project_score, employee_score, and company_score all map their values to the database? This is what I mean:
'Low' maps to 1
'High' maps to 2
'Very High' maps to 3
'Urgent' maps to 4
Is there a way to get the textual output in my views, and separately convert that text back into the numbers before saving? Thanks.

I think what you're asking is as follows
<%= form_for #something do |f| %>
<%= f.select :project_score, [["Low", 1], ["High", 2], ["Very High", 3], ["Urgent", 4]] %>
<%= f.select :employee_score, [["Low", 1], ["High", 2], ["Very High", 3], ["Urgent", 4]] %>
<%= f.select :company_score, [["Low", 1], ["High", 2], ["Very High", 3], ["Urgent", 4]] %>
<% end %>
Alternatively, if you had your Scores in a database table with an id and name column.
<%= form_for #something do |f| %>
<%= f.select :project_score_id, Score.all.map{|s| [s.name, s.id]} %>
<% end %>
Where you would create an association to the score
belongs_to :project_score, :class_name => 'Score'
rather than use the integer. This would also mean you change your fields to project_score_id, employee_score_id, company_score_id
You could also create a custom FormBuilder that would create some form of score_select to make it easier down the road: http://code.alexreisner.com/articles/form-builders-in-rails.html.
When displaying, you'll also need some form of helper method to display the appropriate one:
module ScoreHelper
def score_display(score)
case score
when 1
"Low"
when 2
"High"
when 3
"Very High"
when 4
"Urgent"
end
end
end
# in your view
<%= score_display(#something.project_score) %>
Or if you have took the Score table and belongs_to association approach
<%= #something.project_score.name %>

You can set-up you model to return something like this:
RATINGS = [
["Low", 1],
["High", 2],
["Very High", 3],
["Urgent", 4]
]
Then <%= obj.select Model::FREQUENCY.each { |w| w } %> in the View.

Related

How can I get rails to automatically populate a dynamically generated form?

Let's say I have a model
class A < ApplicationRecord
serialize :vals, Array
end
which stores an array of values. How can I dynamically populate a list of form values? My first guess was to write
<%= #a.vals.each_with_index do |v, i| %>
<%= f.text_field :hints %>
<% end %>
but this is giving me errors.
Submitting this form
<%= form_for #a do |f| %>
<% #a.vals.each do |val| %>
<%= f.text_field :vals, value: val, multiple: true %>
<% end %>
<%= f.submit %>
<% end %>
passes "a"=>{"vals"=>["first", "second", "third"]} in the params to the controller.
As mentioned in the comments, you want to look at the vals from an instance of A not the class A.
Note about the serialize (more for the comments saying it looks wrong) I had never used it, that serialize :vals, Array seems to be working for me
A.create(vals: ['hint 1', 'hint 2']); A.last.vals
# (0.2ms) BEGIN
# SQL (0.4ms) INSERT INTO ... [["vals", "---\n- hint 1\n- hint 2\n"]...
# (0.6ms) COMMIT
# A Load (0.3ms) SELECT "as".* FROM "as" ORDER BY "as"."id" DESC LIMIT $1 [["LIMIT", 1]]
# => ["hint 1", "hint 2"]

Rails select options only seem to send 0

I am trying to use select options in rails
<%= f.select :category, options_for_select(["Select One", "Cell", "Work", "Office", "Home", "Other"],[1,2,3,4,5,6]) %>
Params
def story_params
params.require(:story).permit(:title, :body, :user_id, :category)
but the database table only seems to get "0" whenever my post is submitted, why is this?
I think you need to add like this instead
<%= f.select :category, options_for_select([["Select One", 1], ["Cell", 2], ["Work", 3], ["Office", 4], ["Home", 5], ["Other", 6]]) %>
Hope that helps!
options_for_select accept key and value in nested array format if you didn't pass value it will take key as value
so, you need to pass as key,value pair like [["Select One", 1],["Cell", 2]..etc]
For more reference view this

Setting include_blank for an f.select with options_for_select

I have the following in my View:
<%= f.select :blood_group, options_for_select([
['O+', Membership.blood_groups.keys[0]], ['O-', Membership.blood_groups.keys[1]],
], #user.blood_group) %>
How do I add include_blank attribute to the above? When I just append it at the end, I get the error "wrong number of arguments (given 3, expected 1..2)"
You could do it this way:
<%= f.select :blood_group, [['', nil], ['one', 1], ['two', 2], ['three', 3], ['four', 4], ['five', 5], ['', nil]]
its optional to specify options_for_select note that this add two blanks field at the beginning and in the end.
You can do this following as:
<%= f.select :blood_group, options_for_select([
['O+', Membership.blood_groups.keys[0]],
['O-', Membership.blood_groups.keys[1]]], #user.blood_group, {include_blank: true}, {}) %>
You can refer document at: options_for_select

Displaying Options for select values in view (rails)

I have a simple form, with a select tag, with options for the select. I want to be able to list those selected options on a view. The only way I know how to do this, would be to call the instance variable that has ActionItem.new(action_item_params) in it, with an attribute as the method (in this case, :purpose). In the view, this displays nothing, where I'd like it to display the select tag option the user selected. - New to OOP, Ruby, and Rails - likely a rookie situation. Will read face off in the meantime.
Form:
<div align="center"><h1><%= #client_name.name %></h1></div></br></br>
<div align="center"><strong>Communication Options:</strong></br></br>
<%= form_for(:action_item, url: {controller: "action_item", action: "create"} ) do |f| %>
<%= f.label("Purpose Of This Contact?:") %>
<%= select_tag(:purpose, options_for_select([['Initial conversation/pitch', 1], ['Follow up correspondence', 2], ['Additional selling point', 3], ['New benefits to convey', 4]])) %></br></br>
<%= f.label("Method Of Correspondence:") %>
<%= select_tag(:correspondence_method, options_for_select([['Send an email', 1], ['Tweet on Twitter', 2], ['Make a phone call', 3], ['Send direct mail', 4]])) %></br></br>
<%= f.label("Do I know the contact person? ") %>
<%= select_tag(:know_person, options_for_select([['Yes', 1], ['No (have to find out)', 2]])) %></br></br>
<%= f.label("this field will be added, ONLY if above field is NO: How could you find the contact's name?") %></br>
<%= f.text_field(:contact_name_answer, :size => 50) %></br></br>
<%= f.label("Additional notes") %></br>
<%= f.text_field(:additional_notes, :size => 50) %></br></br>
<%= f.submit("Store Action Item") %></br></br>
<% end %>
And the show page:
<h1>Action Item: </h1>
Added: <strong><%= #action_submission.additional_notes %></strong>, nice job.</br> </br>
Added: <strong><%= #action_submission.contact_name_answer %></strong></br></br>
Added: <strong><%= #action_submission.correspondence_method%></strong></br></br>
I actually found the answer to be: Just use 1 array, rather than an array of arrays. Now, the array looks like:
<%= f.select(:purpose, ['Initial conversation/pitch', 'Follow up correspondence', 'Additional selling point', 'New benefits to convey']) %></br></br>
This worked just fine. Thanks for reading anyway!
Try f.select instead of select_tag.

Rails: nested form binded to an object – problems with select box

I have a nested form model in my Rails app. When I go to edit an object in the model, all of my fields (text_area, check_box, etc.) are populated with data from the database except for the select box. How can I get my select box to also populate when I am using the form to edit existing data from the model?
<%= form_for #test do |f| %>
<%= f.fields_for :questions do |builder| %>
<%= render 'question_fields', f: builder %>
<% end %>
<% end %>
_question_fields.html.erb
<fieldset>
<%= f.text_area :question_text %>
<%= f.select :correct_answer, options_for_select([['A', 1], ['B', 2], ['C', 3], ['D', 4], ['E', 5]]), :prompt => 'Choose the correct answer' %>
<%= f.check_box :question_check %>
</fieldset>
You need to send the selected parameter in options_for_select function call.
<%= f.select :correct_answer, options_for_select([['A', 1], ['B', 2], ['C', 3], ['D', 4], ['E', 5]], :selected => f.object.correct_answer), :prompt => 'Choose the correct answer' %>
Try setting a value for selected.
Refer to: http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-options_for_select
Edit: Can't test it now but I'm pretty sure select will take the array of options by itself. So you shouldn't need options_for_select here - then selectshould set the selected option..
Try this and refer to: http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-select

Resources