Rails selecting a field in grouped_collection_select - ruby-on-rails-3

I'm using this code in my view to create a selection grouped_collection_select(:query, :city_id, #states, :cities, :name, :id, :name, {:selected => "Chicago"}) that looks like this:
I want to have "Chicago" selected by default. How can I get this to work?

Hi on your sample above you can select "Chicago" by defining the selected key index of chicago.
Here's an example:
#city_group =
[
["Wisoncin", [["Lake Geneva", "1"],
["Elkhart Lake", "2"]]],
["Michigan", [["Harbor Country", "3"], ["Traverse City", "4"]]],
["Indiana", [["Bloomington", "5"], ["Valparaiso", "6"]]],
["Minnesota", [["Twin Cities",
"7"], ["Bloomington", "8"], ["Stillwater",
"9"]]],
["Florida", [["Sanibel & Captiva", "10"]]],
["Illinois", [["Chicago", "11"],
["Galena", "12"]]],
]
and in your views add this:
<%= select_tag(:brand_id, grouped_options_for_select(#city_group, selected_key = "11", prompt = nil)) %>
Hope it helps! Enjoy!

Solution: 1
city = City.find_by_name("Chicago")
select(:query, :city_id, option_groups_from_collection_for_select(#states,
:cities, :name, :id, :name, city.id))
Solution: 2
city_obj = City.find_by_name("Chicago")
grouped_collection_select(:query, :id, #states, :cities, :name, :id, :name,
{:object => city_obj})
Solution: 3
#city = City.find_by_name("Chicago")
grouped_collection_select(:city, :id, #states, :cities, :name, :id, :name)

It is possible to pre-select an option, but it's not very clear in the documentation. The first parameter (here :city) has to be the name of an instance variable defined on self. The object stored in that instance variable has to have a method named after the second parameter (here: :id). Now #city.id should return the id of the city you want to have selected.
#city = City.find_by_name("Chicago")
grouped_collection_select(:city, :id, #states, :cities, :name, :id, :name)
I made you a gist with a slightly different example for better understanding. Note: the gist should be executed in a rails console, so that the include works

Related

Concatenate field names in select

I have a form that allows you to select a facility by name then writes the id of the facility to a vale in the database.
<%= f.collection_select(:transfer_to_id, Facility.all, :id, :facility_name, {:include_blank => true}, {:class => 'select'})%>
I'd like to be able to select the facility name but to the right of the facility name display the facility_address in the form. I'm not sure how to do this, possibly an array of some sort or using a helper method.
If anyone can provide some help it would be appreciated.
Here is what ended up working properly for me by creating a Class method.
def facility_name_with_facility_address
"#{facility_name} | #{facility_address}"
end
This is untested so bear with me, but you need to add a method to your Facility model:
def facility_name_with_facility_address
facility_name << " " << facility_address
end
And then in your form you want to change the following:
<%= f.collection_select(:transfer_to_id, Facility.all, :id, :facility_name, {:include_blank => true}, {:class => 'select'})%>
To this:
<%= f.collection_select(:transfer_to_id, Facility.all, :id, :facility_name_with_facility_address, {:include_blank => true}, {:class => 'select'})%>

F Select showing the current value in the Database

I have the following as my f select
How do i modify to show what is in the database?
<%= f.select :phase_names, options_for_select([["Select One", "", #phase_names_string_value], "RFP Stage", "Pre Contract", "Awarded", "Unsuccessful", "Completed"]), :class => 'inputboxes' %>
Phase Names is from a second table in the database.
however each project can only sit in one phase at a time.
Thanks in advance
options_for_select(container, selected = nil)
The container is display\value combination so you need [[value,name],[value,name]] or if its the same [name]
Like ["RFP Stage", "Pre Contract", "Awarded", "Unsuccessful", "Completed"]
Now that you have the container you need something to match the selected value
#current_value = MyModel.find(1).vari # Assume MyModel table with id has col vari=Completed
Then, you can do
select_tag "select_name", options_for_select(["RFP Stage", "Pre Contract", "Awarded", "Unsuccessful", "Completed"].insert(0, "Select One"), #current_value)
Another way to do it is to have a collection of an object that holds the options with lets say :name (displayed) and :value (used as value) where selected has :phase_names = :value
f.collection_select :phase_names, [:name => "rStage", :value => "Pre Contract"] , :value, :name, {:include_blank => 'Select one'}
Which works just as activerecord classes

Rails - how to display value through associations in form_for?

This is my view:
= form_for(#user) do |f|
= f.autocomplete_field #user.city.name, autocomplete_city_name_users_path
On the second line I am trying to display the association, but I am getting
undefined method `London' for #<User:0x00000129bb3030>
The associations:
User belongs_to :city
City has_one :user
The displayed result in the error message (London) is right, but why I am gettng that error message?
The argument to f.autocomplete_field should be the name of a method. The form builder will send this method to #user to get the correct value. Since the value you're interested in is not in user but in an object owned by user, you have a few options:
Add city_name and city_name= methods to your User class:
# app/models/user.rb
def city_name
city && city.name
end
def city_name=(name)
city.name = name # You'll want to make sure the user has a city first
end
If you don't know how to make sure you have a city, you could create one lazily by changing your city_name= method to this:
def city_name=(name)
build_city unless city
city.name = name
end
Then your form would look like this:
= form_for(#user) do |f|
= f.autocomplete_field :city_name, autocomplete_city_name_users_path
Or you could treat this as a nested object. Add this to User:
accepts_nested_attributes_for :city
And use fields_for in your form:
= form_for(#user) do |f|
= f.fields_for :city do |city_f|
= city_f.autocomplete_field :name, autocomplete_city_name_users_path

form_for non-AR model - fields_for Array attribute doesn't iterate

I'm having trouble getting fields_for to work on an Array attribute of a non-ActiveRecord model.
Distilled down, I have to following:
models/parent.rb
class Parent
extend ActiveModel::Naming
include ActiveModel::Conversion
include ActiveModel::Validations
extend ActiveModel::Translation
attr_accessor :bars
end
controllers/parent_controller.rb
def new_parent
#parent = Parent.new
#parent.bars = ["hello", "world"]
render 'new_parent'
end
views/new_parent.html.haml
= form_for #parent, :url => new_parent_path do |f|
= f.fields_for :bars, #parent.bars do |r|
= r.object.inspect
With the code as above, my page contains ["hello", "world"] - that is, the result of inspect called on the Array assigned to bars. (With #parent.bars omitted from the fields_for line, I just get nil displayed).
How can I make fields_for behave as for an AR association - that is, perform the code in the block once for each member of my bars array?
I think the correct technique is:
= form_for #parent, :url => new_parent_path do |f|
- #parent.bars.each do |bar|
= f.fields_for "bars[]", bar do |r|
= r.object.inspect
Quite why it can't be made to Just Work I'm not sure, but this seems to do the trick.
I think that it can be done without the need of each:
= form_for #parent, :url => new_parent_path do |f|
= f.fields_for :bars do |r|
= r.object.inspect
You need to set some methods that are expected in the parent class to identify the collection.
class Parent
def bars_attributes= attributes
end
end
And you also will need to make sure that the objects in the array respond to persisted (so you cannot use strings) :(
I ditched the fields_for and added multiple: true
= form_for #parent, :url => new_parent_path do |f|
- #parent.bars.each_with_index do |bar, i|
= f.text_field :bars, value: bar, multiple: true, id: "bar#{i}"

Using awesome_nested_set in a nested form

I'm using Rails 3.0.7 with awesome_nested_set and I'm trying to create a nested form which will allow me to enter a category and sub categories all in one create form.
Here is my category model, controller & form
category.rb
class Category < ActiveRecord::Base
acts_as_nested_set
end
categories_controller.rb
class CategoriesController < InheritedResources::Base
def new
#category = Category.new
3.times { #category.children.build(:name => "test") }
end
end
form
= form_for #category do |f|
-if #category.errors.any?
#error_explanation
%h2= "#{pluralize(#category.errors.count, "error")} prohibited this category from being saved:"
%ul
- #category.errors.full_messages.each do |msg|
%li= msg
.field
= f.label :name
= f.text_field :name
%p Sub categories
= f.fields_for :children do |child|
= child.text_field :name
.actions
= f.submit 'Save'
The problem here is that I only end up with one sub category in my form and it doesn't have name set to 'test' so I don't believe that it's actually the child of the category showing here.
What am I missing here?
Can this be done?
Is there an easier way?
Update
If I change my form to the following then it displays three sub categories each with name set to 'test'. This will not save correctly though.
%p Sub categories
- #category.children.each do |sub|
= f.fields_for sub do |child|
= child.label :name
= child.text_field :name
%br
Found my answer and wrote a wiki page about it here:
https://github.com/collectiveidea/awesome_nested_set/wiki/nested-form-for-nested-set