Setting multiple attributes select form Rails 3 - ruby-on-rails-3

I have a drop-down menu that lists a collection of locks. I would like to set two params when an option is selected:
:name => l.name (which works with the code below)
:device_id => l.id
<%= f.select(:name, Lock.all.collect {|l| [ l.name ] } ,{:include_blank => true} ) %>
I've tried passing the value in a hidden_field, but the field isn't aware of the lock that was selected. Any input is much appreciated.

Hi you can do this:
<%= select_tag(:name, options_from_collection_for_select(Lock.all, :id, :name, params[:name]) )%>
or in your controller add this code:
#locks = Lock.find(:all)
and in your views
<%= select_tag(:name, options_from_collection_for_select(#locks, :id, :name, params[:name]) )%>
when you submit your form that contains this select_tag the params[:name] will get the selected name from the url of your app.
Hope it helps.

So You need to get two values in controller side ?
Ex:-
I have below values in my db
ID Name
4 gggg
5 tttt
2 iiii
So dropdown will show the all names gggg,tttt,iiii if you select tttt from dropdown in server you required both 5, tttt right?
Then you need to use below code
In controller
#locks = Lock.all.map{|l| [l.name, "#{l.id};#{l.name}"]}
In your view
<%= select_tag(:name, options_from_collection_for_select(#locks) )%>
So it will send the both id and name values saparated by ";" .
In your controller you need to split by ";"

Related

Can I add logic to a rails 3 hidden field?

I have a form to submit data and I want to automatically set one field depending on whether all the other fields are filled out or not. If they are all completed, the field will be "complete", if not it will be set to "draft".
So I have the hidden field like this:
<%= f.hidden_field :status, :value => "draft" %>
to make it default to draft. BUT, can I add logic that says it will be "complete" if all the other fields are filled out and if so how?
Here is how to do it on the client-side with jquery, assuming your model is named foo:
<script type='text/javascript'>
$(document).ready(function() {
$('input[name*="otherfields"]').on('change', function() {
var othercount = 0;
$('input[name*="otherfields"]').each(function() {
if ( $(this).is(':checked') )
othercount += 1;
});
if ( othercount == 2 )
$('#foo_status').attr('checked',true)
else
$('#foo_status').attr('checked',false)
});
});
</script>
<%= check_box_tag :item1 , '1', false, :name=>'otherfields[1]' %>
<%= check_box_tag :item2 , '2', false, :name=>'otherfields[2]' %>
<%= f.hidden_field :status, :value => "draft" %>
Assuming no other client-side events have to take place when the the status changes, it would be best practice to place this kind of business logic inside of your model as a callback, e.g. (replace Foo and fieldx with your model and field names):
class Foo < ActiveRecord::Base
before_save :default_status
def default_status
if field1 && field2 && field3 && field4
self.status = 'completed'
else
self.status = 'draft'
end
end
end
Yes, you can do that in the controller.
Lets say the form directs you to the create action.
In the create action of the controller, you can check if all the fields are completed by looking at params and then use if statement to assign appropriate value to status before saving
This would be done with javascript, possibly jQuery. However, why would you design it this way? Could you not do this on the server side?

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

Selected option not working for select

I have this select which works fine, but default the select is empty and doesn't show the selected value (which is filled correctly):
<%= f.select(:relationgroup, options_for_select(#relationgroups), { :selected => #relation.relationgroup, :include_blank => true}) %>
Any idea why? Thanks!
Try it that way:
<%= f.select(
:relationgroup,
options_for_select(#relationgroups, #relation.relationgroup),
:include_blank => true
) %>
Not sure, but maybe it'll work better.
Anyway, assuming Relationgroup is some model with id and name (or any other attribute that you want to be visible in select options) attributes, and you're using default relationgroup_id foreign key in your model you'd better construct your select like that:
<% f.select(
:relationgroup_id,
options_from_collection_for_select(#relationgroups, :id, :name),
:include_blank => true
) %>
It'll choose selected value based on object.relationgroup_id where object is the model you're building form for. See docs for more information.

how to create dropdown from a hash in rails 3

In rails 3, how to create a Dropdown from hash
I have following code in my User class
class User
... other codes
key :gender, Integer # i use mongo db
class << self
def genders()
genders = {
'1' => 'Male',
'2' => 'Female',
'3' => 'Secret'
}
end
end
end
In the user form, i am trying to create a gender dropdown list
<%= f.collection_select nil, :gender, User.genders, :key, :value %>
but it complain
undefined method `merge' for :value:Symbol
So what is the proper way to create the dropdown?
Thanks
This should work:
<%= f.collection_select :gender, User.genders, :first, :last %>
Edit: Explanations:
collection_select will call each on the object you give (User.genders here) and the two methods (first and last here) on each object. It's roughly equivalent to something like this:
User.genders.each do |object|
output << "<option value=#{object.first.inspect}>#{h object.last}</option>"
end
When you call each on a Hash, it yields an Array of two values (the key and the value). These values can be retreived with the first and last methods.