divz
divz

Reputation: 7957

dropdown list in ruby on rails

I want to display values to drop down list from Database. For that in my controller class i did the following to get the values from db and its getting properly.

 @value = Message.find(:all)

<Message ID: 14448, SlNo: 609">, #<Message ID: 14448, SlNo: 610">

How can i display the SlNo values to drop down list.Here is the code am using and getting error!I don't know how to set values inside a collection_select.Please help me!!

<% @value.each do |d| %>
<%=collection_select(:value, :id, @value, :id, { selected: params.fetch(:value, {})[:id].to_i, :prompt => "-Select a device" }) %>
<% end %> 

Table names getting

["UniqueDeviceID", "SlNo"] 

Model

class MessageDetail < ActiveRecord::Base
  # attr_accessible :title, :body

  set_table_name 'DeviceDetails'
set_primary_key 'SlNo'
end

Upvotes: 1

Views: 3266

Answers (2)

Satishakumar Awati
Satishakumar Awati

Reputation: 3798

# START
f.collection_select :id, Message.all(:order => "name"), :id, :name, :include_blank => true
# END

OR

# START
messages_arr = []    
messages = Message.all(:order => "name")
messages.each do |msg|
 messages_arr << [msg.name, msg.id]
end
f.select(:id, options_for_select(messages_arr), {:include_blank => 'Include All'}, {:class=>"span12"})
# END

Upvotes: 1

jvnill
jvnill

Reputation: 29599

instead of

<% @value.each do |d| %>
  <%=collection_select(:value, :id, @value, :id, { selected: params.fetch(:device, {})[:id].to_i, :prompt => "-Select a device" }) %>
<% end %> 

use

<%= collection_select :value, :id, @value, :id, :S1No, { selected: params.fetch(:device, {})[:id].to_i, :prompt => "-Select a device" } %>

UPDATE: explanations for passed parameters

  • :value = a symbol representation of the record you want to update, it may also not be an instance record but just a symbol that will be used in the naming convention of the select tag
  • :id = the column that you wish to update
  • @value = the collection to show the choices
  • :id = the method you want to use that will be passed as the value of the selected value
  • :S1No = the method that will be used as the label for the options of the select tag

Upvotes: 2

Related Questions