Rails form_for with collection_select - ruby-on-rails

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

Related

How can I render option field from other database table in rails?

I have a model Responsibility with has one text field of responsibility. Other model is Stage, in Stage form field there is a text_field responsibility I want to render an option list from responsibilities table how can i do that in rails?
routes.rb
resources :projects do
resources :responsibilities
resources :stages
end
stage _form.html.erb
<%= form_with(model: stage, url: [#project, stage], local: true) do |form| %>
<div>
<%= form.label :responsibility, :class=>"required" %>
<%= form.text_field :responsibility %>
</div>
<div>
<%= form.submit %>
</div>
<% end %>
How can I render responsibilities list as an option in stage responsibility form field?
what is tried is:
stage _form.html.erb
<div>
<%= form.label :responsibility %>
<%= select_tag "colors", #responsibilities , multiple: true %>
</div>
stages_controller.rb
def new
#stage = Stage.new
#project = Project.find(params[:project_id])
#responsibilities = #project.responsibilities
end
I was able to render form but in responsibility field none of the responsibility was accessed as option.
select_tag accepts as a second parameter string that contains options as a string.
Rails provides some helper methods that are useful for generation of those <option>
tags
options_from_collection_for_select, options_for_select
If you inspect with your browser's developer tools the html code of the <select> tag you will see something like this:
<select name="colors[]" id="colors" multiple="multiple">
#<Responsibility::ActiveRecord_Relation:0x00007f3f72cc7eb0>
</select>
This is because select_tag calls to_s method of #responsibilities collection.
The correct way of creating select_tag would looks something like this:
<%= select_tag "colors", options_from_collection_for_select(#responsibilities, :id, :name) , multiple: true %>
There is another way to build select field using the FormBuilder method collection_select. It might look something like this:
<div>
<%= form.label :responsibility %>
<%= form.collection_select :responsibility, #responsibilities, :id, :name, prompt: true %>
</div>
I hope this answer will be useful.

concating checkboxes in Ruby on Rails

I have a field called delivery_day which is of type string in delivery_preference model.
In form, I want to provide 7 checkboxes for each day like Sunday,Monday,etc., and later want to concat.
For example if a user checks Sunday and Friday, I want to concat & store it as "Sunday,Friday" in delivery_day field.
Thanks in Advance!!
You can design your form like this -
<%= form_for #delivery_preference do |f|%>
<%= f.check_box :delivery_day, {multiple: true}, "Sunday" %>Sunday
<%= f.check_box :delivery_day, {multiple: true}, "Monday" %> Monday
<%= f.submit "Add" %>
<% end %>
After submitting the form, you can get your check box selections in your controller as follows:
def your_action_name
params[:delivery_preference][:delivery_day].delete("0")
DeliveryPreference.create(delivery_day: params[:delivery_preference][:delivery_day].join(","))
end
Hope it helps!
Might have better solutions, but when I encountered similar problem, I used check_box_tag to solve it.
<%= check_box_tag "delivery_preference[delivery_day][0]", 'monday' %>Monday
<%= check_box_tag "delivery_preference[delivery_day][1]", 'tuesday' %>Tuesday
<%= check_box_tag "delivery_preference[delivery_day][2]", 'wednesday' %>Wednesday
<%= check_box_tag "delivery_preference[delivery_day][3]", 'thursday' %>Thursday
<%= check_box_tag "delivery_preference[delivery_day][4]", 'friday' %>Friday
<%= check_box_tag "delivery_preference[delivery_day][5]", 'saturday' %>Saturday
<%= check_box_tag "delivery_preference[delivery_day][6]", 'sunday' %>Sunday
then you will receive an array like { deliver_day: ['monday', 'tuesday'] } in you controller. You can choose to concat in your controller, and then save, or you can move the logic to your model.
in your controller, you strong parameter should be like
params.require(:delivery_preference).permit(.., :deliver_day => [])
to permit the array.
I do not have enough reputation to leave a brief comment yet. However, does your migration have delivery_day have something similar to t.boolean :public, default: true_or_false_here within it?
If so, within the form, you could have something like:
...
<div class="form-group">
<%= f.label :public, class: 'checkbox' do %>
<%= f.check_box :public %> Monday
<% end %>
</div>
<div class="form-group">
<%= f.label :public, class: 'checkbox' do %>
<%= f.check_box :public %> Tuesday
<% end %>
</div>
...
After above, you could designate (via boolean logic) your "concat & store it as "Sunday,Friday"

Is there a way to set a distinct ID and name for a text_field in Rails 2?

I've got a Rails 2 site I'm trying to add a form handler to, but I'm running into problems converting the html form fields into form handler fields.
The form code begins with:
<% form_for #newsavedmap, :html=>{:id=>'createaMap'} do |f| %>
I keep getting errors when I try things like
<%= text_field :newsavedmap, :html=>{ :value => 'New Map', :name=>'newsavedmapname', :id=> 'savedmap_name', :size => '30' } %>
Error:
ActionView::TemplateError (wrong number of arguments (1 for 2)) on line #284 of app/views/layouts/maptry.html.erb:
Here are the fields. How can I convert these to form handler fields in Rails 2?
<input id="savemap_name" name="newsavedmapname" size="30" type="text" value="New Map"></p>
<select id="startdrop" name="startthere">
<OPTIONS HERE>
</select>
<select multiple id="waypoints" class="mobile-waypoints-remove" name="waypointsselected[]">
<OPTIONS HERE>
</select>
Thanks for any help you can provide!
Edit 1 Error Code for the Text_Field
Using Bigxiang's approach, I get
Processing NewsavedmapsController#create (for IP at Date Time) [POST]
Parameters: {"endhere"=>"", "endthere"=>"SAMPLE ADDRESS 1", "newsavedmap"=>{"newsavedmapname"=>"test Map"}, "startthere"=>"SAMPLE ADDRESS 2", "starthere"=>"", "optimize"=>"on"}
ActiveRecord::UnknownAttributeError (unknown attribute: newsavedmapname)
The line with "newsavedmap"=>{"newsavedmapname"=>"test Map"} should just read
"newsavedmapname"=>"test Map"
How can I do this? My controller starts with:
def create
#newsavedmap = Newsavedmap.new(params[:newsavedmap])
#newsavedmap.name = params[:newsavedmapname]
try this:
<% form_for #newsavedmap, :html=>{:id=>'createaMap'} do |f| %>
<%= f.text_field :newsavedmapname :id=>"savemap_name", :size=>30, :value=>"New Map"%>
<%= f.select :startthere, YOUR_COLLECTIONS, {}, {:id=>"startdrop"}%>
<%= f.select :waypointsselected, YOUR_COLLECTIONS, {}, {:id=>"waypoints", :class=>"mobile-waypoints-remove", :multiple => true}%>
<% end %>
make sure YOUR_COLLECTIONS should be an array like ['a', 'b', 'c'] or [['name1', id1],['name2', id2],['name3', id3]].
If you persist the parameter is "newsavedmapname"=>"test Map", try this:
<% form_for #newsavedmap, :html=>{:id=>'createaMap'} do |f| %>
<%= text_field_tag :newsavedmapname, "New Map", :id=>"savemap_name", :size=>30%>
<%= select_tag :startthere, options_for_select(YOUR_COLLECTIONS), {:id=>"startdrop"}%>
<%= select_tag :waypointsselected, options_for_select(YOUR_COLLECTIONS), {:id=>"waypoints", :class=>"mobile-waypoints-remove", :multiple => true}%>
<% end %>
But I don't understand why not use parameter's name as same as the column's name. For example, I see your newsavedmap model has a column named "name". you can use it directly
<% form_for #newsavedmap, :html=>{:id=>'createaMap'} do |f| %>
<%= f.text_field :name , :value=>"New Map" %>
<% end %>
in your controller , you can delete line #newsavedmap.name = params[:newsavedmapname]
def create
#newsavedmap = Newsavedmap.new(params[:newsavedmap])
if #newsavedmap.save
#######
end
end

Ruby on rails drop down box Beginner lvl

So I am a beginner in ROR, like I know it for a month (school assignment and we don't get a cursus we need to use 'google')
So I want a dropdown box with a list of all my cities. Then if I pick a city I need to save the city_id in my database together with the date. The code I have so far seem to work except when I click on save it says that city is empty (and it can't be empty because of the failsave)
this is my code
<div class="field">
<%= f.label :stad_id %><br />
<% cities_array = Stad.all.map { |stad| [stad.naam, stad.land] } %>
<%= select_tag(Stad, options_for_select(cities_array)) %>
</div>
<div class="field">
<%= f.label :datum %><br />
<% datum = Time.now.to_s(:db) %>
<%= f.text_field :datum, :value => datum.inspect, :readonly => true %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
I don't really know what I am doing wrong except I have an eery feeling I don't actually give the command to save it.
help is much thanked
sincerely
Robin
There are a few things I notice here that are wrong.
1) Put the creation of the cities_array into your controller, not in your view:
def edit
#something = Something.find(params[:id])
#cities_array = ... whatever ...
end
2) When creating your cities_array, you need to specify the ID of the city as the second parameter, like this:
#cities_array = Stad.all.map { |stad| [stad.naam, stad.id] }
3) The select_tag call isn't for Stad, it's for the model you're trying to save. For example, your form might look like this:
<%= form_for #something %>
<%= f.label :city %>
<%= f.select :city_id, #cities_array %>
# or!
<%= select :something, :city_id, #cities_array %>
<% end %>
I hoep this clears things up for you.

Newbie Rails 3 - select_tag - numeric values

In a form I want a selectbox with the values 1 to 30, and store the value in a db-column. Is there a helper for this? I looked at the select_tag but did not find a good solution.
Can someone help?
I usually put the acceptable range of values in my model
# app/models/widget.rb
class Widget < ActiveRecord::Base
RATING_VALUES = (1..10)
end
And then I can reference that in the view:
# app/views/widgets/_form.html.erb
<%= form_for #widget do |f|
<fieldset>
<%= f.label :rating %>
<%= f.select :rating, Widget::RATING_VALUES %>
</fieldset>
<!-- etc -->
<% end %>
Use the select_tag when you require a drop-down selection box populated with data not sourced from a database
erb:
<%= f.select "make_num", 1..30 %>
haml:
= f.select "make_num", 1..50
or (better MVC)
create the my_range = 1..30 in your controller
my_range = 1..30
and then in your view:
erb:
<%= f.select "make_num", my_range %>
haml:
= f.select "make_num", my_range
or (best MVC)
Use clem's solution :)

Resources