Rails: nested form binded to an object – problems with select box - ruby-on-rails

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

Related

Display checkbox instead of drop down select

I have the following form:
<%= form_for #user do |f| %>
<div class="form-group">
<%= f.label :extra_act %>
<%= f.select(:extra_act, [['Act 1', 1],['Act 2', 2], ['Act 3', 3]], class: 'form-control', required: true) %></br>
</div>
<%= f.submit 'Submit', class: 'btn btn-primary' %>
<% end %>
Is there a way to offer checkboxes instead of the drop down select menu here? I have found checkboxes on the ruby website, but I only want users to have the option of selecting one checkbox.
This will work with rails 4+
You want the user to select only one value so instead of check_box you need radio button. Here is how you can do it(syntax):
collection_radio_buttons(method, collection, value_method, text_method, options = {}, html_options = {}, &block)
Something like this with your code:
f.collection_radio_buttons(:extra_activity_id, ExtraActivity.all, :id, :title, html_options: { class: 'form-control' }
For rails 3 you will need to loop on the extra activities:
<% ExtraActivity.all.each do |ea| %>
<%= f.radio_button :extra_activity_id, ea.id %>
<% end %>
As you don't have this is database and you are using an array then do it like this, it may work:
f.collection_radio_buttons(:extra_activity_id, [['Act 1', 1],['Act 2', 2], ['Act 3', 3]], :last, :first, html_options: { class: 'form-control' }
You can either use a single select list (meaning multiselect attribute should be off) or a radio group.
Whichever suits your needs.

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.

How do I pass the option_from_collection_for_select results in a single param?

I have a form where you have to select any number of courses that are prerequisites for certain classes. Basically, course1 -> list of all courses where you choose which ones are prereqs. Then course2 -> and so on. The forms are perfect, but when I submit it, the params in the next page are in a weird format.
course[1][]:1
course[1][]:2
course[2][]:2
#course is Course.all
<% #course.each do |course| %>
<div>
<%= label_tag "course[#{course.id}]", course.title %>
<%= select_tag "course[#{course.id}]", options_from_collection_for_select(#course, "id", "title"), multiple: true %>
</div>
<% end %>
How can I pass the final params as
course[1]: [1, 2]
course[2]: [2]
Thanks!
Please replace the select tag with below tag and try.
<%= select_tag "course[][#{course.id}]", options_from_collection_for_select(#course, "id", "title"), multiple: true %>
I Hope this will help.

Rails - map form values to database

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.

Rails form_for with collection_select

I'm trying to create a field that creates an instance of the Ranking class. It has a comment field already which sets the params[:ranking][:comment] but now I want to add a drop down that displays something like:
1: horrible, 2: poor, 3: mediocre, 4: good, 5: great
I would like these to set the params[:ranking][:score] to a value 1-5 so that in my create method I can do something like this:
#ranking = Ranking.new( #....
:score => params[:ranking][:score])
My form looks like this right now:
<%= form_for([#essay, #ranking]) do |f| %>
<%= render 'shared/error_messages', :object => f.object %>
<div classs="field">
<%= f.text_area :comment %>
</div>
<div classs="field">
<%= #something here!%>
</div>
<div class="actions">
<%= f.submit "Submit" %>
</div>
<% end %>
I know that I need to use the collection_select but I haven't been able to get it working.
You should just be able to use the regular select helper for something like that:
f.select :score, [['horrible', 1], ['poor', 2], ['mediocre', 3], ['good', 4], ['great', 5]]
You would use collection_select if you had a model for the scores. Something like:
f.collection_select :score_id, Score.all, :id, :name
See the API docs for collection_select

Resources