I'm a Rails beginner and I'm working on a preexisting Rails 2 project. In my application, I tried converting a select dropdown field to a form_handler f.select, but I'm getting this error:
undefined method `location.masterlocation.name
Here is my attempt:
<% form_for #newsavedmap, :html=>{:id=>'createaMap'} do |f| %>
<%= f.select(:start, options_from_collection_for_select(#itinerary.locations, "location.masterlocation.street_address, location.masterlocation.city, location.masterlocation.state, location.masterlocation.zip", "location.masterlocation.name"), :id => "startdrop")%>
Here is the original dropdown field:
<select id="startdrop">
<option value="">
<% for location in #itinerary.locations %>
<option value="<%= location.masterlocation.street_address %> <%= location.masterlocation.city %>, <%= location.masterlocation.state %>, <%= location.masterlocation.zip %>"><%= location.masterlocation.name %></option>
<% end %>
</select>
Thanks in advance for your help!
edit 1
I've gotten much closer using this code:
<%= f.select :start, options_for_select(#itinerary.locations.map{ |c| [c.masterlocation.name, c.masterlocation.street_address]}),{}, :id=>"startdrop", :name=>"startthere" %>
The problem is that I want to include the city, state, and zip in the value, all separated by commas. Any ideas about how to do this?
<%= f.select :start, options_for_select(#itinerary.locations.map{ |c| [c.masterlocation.inst_name, c.masterlocation.street_address AND , AND c.masterlocation.city AND , AND c.masterlocation.state AND, AND c.masterlocation.zip]}),{}, :id=>"startdrop", :name=>"startthere" %>
THIS WORKS!
Maptry Helper:
module MaptryHelper
def options_for_select(locations)
locations.map do |location|
[location.masterlocation.name, location_string(location.masterlocation)]
end
end
def location_string(masterlocation)
"#{masterlocation.street_address}, #{masterlocation.city}, #{masterlocation.state}, #{masterlocation.zip}"
end
end
View
<%= f.select :start, options_for_select(#itinerary.locations),{}, :id=>"startdrop", :name=>"startthere" %>
Place the following in a helper file
def select_options_for_locations(locations)
locations.map do |location|
[location_string(location.masterlocation), location.masterlocation.street_address]
end
end
def location_string(masterlocation)
"#{masterlocation.city}, #{masterlocation.state}, #{masterlocation.zip} #{masterlocation.name}"
end
Then in your view, you can use the following
= f.select :start, select_options_for_locations(#itinerary.locations), {}, :id => "startdrop"
Related
My starting place was this discussion: Syntax for form_for when building an array from checkboxes
I have a call to my model passing back an array of valid options. This array then makes a series of check_box_tag
<%= form_for #game, :url => wizard_path do |f| %>
<div>
<% #game.select_races.each do |a| %>
<%= f.label a %>
<%= check_box_tag 'game[races][]', a , true %>
<% end %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
This successfully creates an array called 'races' containing the desired output. The problem is that it doesn't actually update the races attribute. So my races attribute is still nil.
I'm sure this is a painful Rails beginner question. Any help is appreciated.
UPDATE
My allowed params were:
def game_params
params.require(:game).permit(:shattered_empire, :shards_of_the_throne, :number_of_players, :rules, :strategy_cards, :players, :races)
end
Which needed to be updated to:
def game_params
params.require(:game).permit(:shattered_empire, :shards_of_the_throne, :number_of_players, :rules, :strategy_cards, :players, {:races => []})
end
I would like to have the option value changed from the users name to the users ID on the option value in html.
For example:
<option value="John">John</option>
<option value="Jim">Jim</option>
<option value="Kelly">Kelly</option>
<option value="Monica">Monica</option>
<option value="Ralp">Ralp</option>
This is what my html is outputting, and i would like the value to be the users id, such as:
<option value="1">John</option>
<option value="2">Jim</option>
<option value="3">Kelly</option>
<option value="4">Monica</option>
<option value="5">Ralp</option>
I would also like it to be dynamic so when more and more users come I do not have to manually enter their names.
My rails for currently looks like this:
<%= form_tag '/login', method: 'post' do %>
Name:
<br/>
<%= select_tag :user_id, options_for_select(#users) %>
<br/>
<br/>
<%= submit_tag 'Login' %>
<% end %>
And my controller as such:
def login_user
user = User.find_by_name(params[:user_id])
if user
session[:user_id] = user.id
redirect_to user_path(user)
return
end
flash[:error] = 'Sorry that user not in the system.'
redirect_to root_path
end
Could someone please help point me in the right direction. Thank you in advance.
I don't understand what you mean by "dynamic". But following should fix your select issue
<%= form_tag '/login', method: 'post' do %>
Name:
<br/>
<%= select_tag :user_id, options_for_select(User.all.collect{|u| [u.name, u.id]}) %>
<br/>
<br/>
<%= submit_tag 'Login' %>
<% end %>
Got it, I used this instead:
<%= collection_select(:user, :id, User.all, :id, :name) %>
this gave me a drop down tab with user value and user name. Thank you all!
Is it possible to pass the value of checked check_box_tags within a form_for in Rails inside a hash?
Here is a very generic, basic version of the form:
<%= form_for(:object, :url => { :action => 'create', :id => params[:id]}) do |f| %>
<p>Field_a: <%= f.text_field(:field_a) %></p>
<p>Field_b: <%= f.text_field(:field_b) %></p>
<p>Field_c: <%= f.text_field(:field_c) %></p>
<p>Check boxes:</p>
<% check_box_choices_object_array.each do |s| %>
<%= check_box_tag(s.name, 1, false) %>
<%= .name %><br />
<% end %>
<%= submit_tag("Create") %>
<% end %>
Outputs roughly:
Field_a ___________________
Field_b ___________________
Field_c ___________________
Check boxes:
[] box_a
[] box_b
[] box_c
[] box_d
[] box_e
[] box_f
[] box_g
My problem is that since the available check boxes aren't actual fields in the object's table in the database (i.e. I'm not using check_box(:field) in the form), each checked check box gets passed as an individual parameter (i.e. "box_a" => "1", "box_b" => "1", "box_e" => "1"). I would like them to be passed as such:
:checked_boxes => {"box_a" => "1", "box_b" => "1", "box_e" => "1"}
This way, I can access them easily with params[:checked_boxes].
How do I do this, or, better yet, is there a better solution (I'm new to rails)?
I think you'd get the results you want if you wrap the checkboxes iterator in a fields_for :checked_boxes tag - or at least get you close to the results you want.
<%= form_for(:object, :url => { :action => 'create', :id => params[:id]}) do |f| %>
<p>Field_a: <%= f.text_field(:field_a) %></p>
<p>Field_b: <%= f.text_field(:field_b) %></p>
<p>Field_c: <%= f.text_field(:field_c) %></p>
<p>Check boxes:</p>
<%= f.fields_for :checked_boxes do |cb| %>
<% check_box_choices_object_array.each do |s| %>
<%= cb.check_box(s.name, 1, false) %>
<%= .name %><br />
<% end %>
<% end %>
<%= submit_tag("Create") %>
<% end %>
you can deal with no database attributes and models using attr_accessor
class Thing < ActiveRecord::Base
attr_accessible :name
attr_accessor :box_a, :box_b, :box_c
end
This way you can call these attributes in your form.
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
Right now, I'm using the form_for.select and options_for_select rails helpers to create a select box with the data from the model. However, what I really need is a combobox like the one introduced with HTML5:
<input type=text list=browsers >
<datalist id=browsers >
<option> Google
<option> IE9
</datalist>
Is there a rails helper for creating such elements?
No, but it's quite easy to setup your own form builder helper method to achieve such a result, a simple example would be:
app/form_builders/combobox_form_builder.rb
class ComboboxFormBuilder < ActionView::Helpers::FormBuilder
include ActionView::Context # for nested content_tag
include ActionView::Helpers::FormTagHelper #for sanitize_to_id method access
def combobox_tag(name, options, opts= {})
#template.content_tag(:input, :name => name, :id => sanitize_to_id(name), :type => "text", :list => opts[:list_id]) do
content_tag(:datalist, :id => opts[:list_id]) {options}
end
end
end
After restarting your server you can implement your new combobox using the form builder by specifying a builder argument in your form_for call:
<%= form_for #foo, builder: ComboboxFormBuilder do |f| %>
<%= f.combobox_tag(:browser, options_for_select(["Firefox", "Chrome", "IE9"]), :list_id => "list")%>
<% end %>
Output HTML:
<input type="text" name="browser" list="list" id="browser">
<datalist id="list">
<option value="Firefox">Firefox</option>
<option value="Chrome">Chrome</option>
<option value="IE9">IE9</option>
</datalist>
Keep in mind that both IE & Safari do not offer support for the HTML5 Datalist.
<%= form_for #person do |f| %>
<%= f.label :first_name, "First Name" %>:
<%= f.text_field :first_name, list: 'first-name' %>
<datalist id="first-name">
<% Person.all.each do |person| %>
<option value="<%= person.first_name %>"></option>
<% end %>
</datalist>
<%= f.submit %>
<% end %>
You may also want to do distinct:
<% Person.select(:first_name).distinct.each do |person| %>
Just example from my code:
= form_tag controller:'beer', action: 'create' do
= text_field :beer, :name, list: 'beer-name'
%datalist#beer-name
- Beer.all.each do |beer|
%option{value: beer.name}