select field in rails - ruby-on-rails

How I can to pass an array like generated by a controler with the following code:
tipos= Type.all
#listadotipos=[]
tipos.each do |h|
#listadotipos.push(h.name)
end
The last code generate an array called #listadotipos. This array is passed to a html.erb view and I want to show all array components inside a Select field in the view.
The select field works this:
<%= f.select :make, options_for_select(["option1", "option2"]) %>
How I can do this. Please help me.

First of all your controller code can be cleaned up like so:
#listadotipos = Type.all.map(&:name)
Your view code should work if you use the variable instead of your hard coded array:
<%= f.select :make, options_for_select(#listadotipos) %>

With the below code inside the controller :
#listadotipos = Type.all.map { |type| [ type.name, type.id ] }
You can write as below :
<%= f.select :make, #listadotipos %>
Read 3.2 Select Boxes for Dealing with Models guide.

Try this in view
<%= f.select :make, Type.all.collect(&:name) %>
For id
<%= f.select :make, Type.all.collect{|type| [type.name, type.id] } %>

This are the solution. And I dont need code into the controller:
<%= f.select :make, options_from_collection_for_select(Type.all, :id, :name) %>
Thanks all

Related

Using a variable with many values for a database query in rails

I am facing this difficulty. This works for me :
<% cat_st = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29 %>
<%= Categories.where(cat_id: [cat_st]).distinct.count(:af_id) %>
However, I need to create the cat_st string from my GET parameters. When I create it as a string, it gets only the first integer. Actually, I really don't know what the cat_st variable is. I tried to create an array, but it doesn't work. Any ideas?
( it doesn't work)
<% cat_st = '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29' %>
<%= Categories.where(cat_id: [cat_st]).distinct.count(:af_id) %>
cat_st = '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29'
cat_array = cat_st.split(',')
Categories.where(cat_id: cat_array).distinct.count(:af_id)
There may be a better solution for what you're trying to achieve if you give some additional details about what you're trying to do, seems like it should be some sort of search form that passes multiple ids. Something like this for example:
class Search
include ActiveModel::Model
attr_accessor :category_ids
end
<%= form_for Search.new, url: 'whatever_the_url_is' do |f| %>
<div class="field">
<%= f.label :category_ids %>
<%= f.collection_check_boxes :category_ids, Category.all, :id, :name %>
</div>
<% end %>
search = Search.new(search_params)
Categories.where(cat_id: search.category_ids).distinct.count(:af_id)
You can pass just a range to the where method so:
Categories.where(cat_id: (1..29)).distinct.count(:af_id)
and to pass data via GET request just use a limitation:
http://host.domain/controller/action?begin=1&end=29
controller:
def action
#cat = Categories.where(cat_id: (params[:begin].to_i..params[:end].to_i)).distinct.count(:af_id)
end
then render the view using #cat variable.
If you add square brackets to the param name in the URL query, Rails (specfically Rack) will interpret that as an array:
http://some.route.url/path?foo[]=bar&foo[]=buzz
The controller will read params[:foo] as ['bar', buzz']
However, I have a feeling that use case problem you are attempting to solve might have a much simpler solution. Care to go into any more detail?

How can I list items in rails for options_for_select?

I'm using rails 4 and I'd like to list categories in a select drop down menu. How can I do that? I have a form that looks like so:
<%= f.select (:category_id),
options_for_select([
["Maths", 1],
["Physics", 2]
])
%>
but of course, the content has to be dynamic from database, so I tried the following:
options_for_select([
#categories.each do |c|
[c.title, c.id]
end
])
but that outputs #<Category:randomdigetshere> if I try to get the same output outside of that options_for_select it works and the title / id is being displayed as it should.
What's the right way of doing it?
You could do
<% categories_array = Category.all.map { |category| [category.title, category.id] } %>
<%= options_for_select(categories_array) %>
or
<%= options_from_collection_for_select(Category.all, :id, :title) %>
You can make it even shorter using collection_select
Assuming your #categories's format is:
#categories = Category.all
You can do:
options_for_select(#categories.map { |category| [category.title, category.id] })
I cannot tell you how many times I've looked this up and fat fingered my way around it. Here's my take on it which includes:
default text displayed in select drop down
a method call on the instance which merges first_name and last_name attributes
sets :selected so it is available when editing
sets a class (useful for simple_form integration)
select_tag(:doctor_id, options_for_select(["Select doctor"] + #doctors.map{ |doctor| [doctor.full_name, doctor.id] }, :selected => :doctor_id), :class => 'form-control')
Remember that this needs to be wrapped in outputting tags i.e. <%= and %>
What options_for_select does is take an array and format into the native html options tag format along with the selected attribute, etc. What's going on here is that we initialize the array with a element titled "Select doctor" and then we append to that an array of items which look like ["Bob Smith", 1]

Way to define id or class for options_for_select in rails?

how can we define id for this rails select statement , i have tried doing in this way like
<%= f.select :state, options_for_select(Contact::STATES), :id=>"state_job" %>
but it is not showing any id when i inspect it in the browser. Please help me out
<%= f.select :state, options_for_select(Contact::STATES) %>
The select tag helper looks for options, then html_options, you just need to make sure your id is in the right place (html_options) by passing something to the options parameter:
<%= f.select :state, options_for_select(Contact::STATES), {}, {:id=>"state_job"} %>

Iterate through records in view and create text_fields

I have a table: family_children (the model is family_child) where family has many children.
I get the children like this:
#family_children = #family.children
where .children is an association to family_children table.
In a view I want to iterate through the children, and put each of them in a text_field. Of course, I need these fields as params when the page is POSTing. I.e. I think that I should get the children as an array.
How can I achieve that?
I mean, if I'll write
<%= text_field 'child', 'name' %>
I don't really get what I need.
Try something like this in your view:
<% #family_children.each_with_index do |c, i| %>
<%= text_field_tag "children[#{i}]", c.name %>
<br />
<% end %>
This should return params[:children] after posting which should be an array. I wasn't sure of the name of the property you want to show in the text box so I have assumed it is called 'name'.
Actually, #family_children object acts as array, so you can simply call each or map on it.
Do you want to put the children's names in a form field or in the view as just a part of the page text? could you include the view file?
since u want the family_children data to be POSTed, u need to see the concept of nested attributes. please see http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html and http://apidock.com/rails/ActionView/Helpers/FormHelper/fields_for
class Family
has_many :children, :class => "FamilyChild"
accepts_nested_attributes_for :children
end
class FamilyChild
belongs_to :family
end
and the form can be as
<%= form_for #family do |p| %>
First name: <%= p.text_field :first_name %>
Last name : <%= p.text_field :last_name %>
<%= fields_for #family.children do |c| %>
<%= c.text_field :child_name %>
<% end %>
<%= f.submit %>
<% end %>

add class to rails select

I need to add a class to my select.It seems to be easy but I'm not able to figure it out.
I'm trying this but the class doesn't show up:
<%= f.select :dr_state, us_states ,:selected=>cr_dovi.try(:dr_state),:class=>"dr_state" %>
When I don't need to make that select auto-select It works in this way:
<%= f.select :dr_state, us_states ,{},:class=>"dr_state" %>
I have been trying to figure it out for about an hour please help me.
Try the following, I think Ruby may be parsing both of your final parameters into the same hash:
<%= f.select :dr_state, us_states , { :selected=>cr_dovi.try(:dr_state) }, :class=>"dr_state" %>

Resources