Monday, December 21, 2009

drop down list/collection selection

I have a simple application just like blog tutorial in the book 'Agile Web Development with Rails', it has two models:
class Log < ActiveRecord::Base
belongs_to :product
end

class Product < ActiveRecord::Base
has_many :logs
end
Product has a part_number_id column which Log reference to. Log was created using scaffold while Product was created using script/generate model.

on the new.html.erb and edit.html.erb files for logs, I need to show all available products in a drop down list so user can choose the product and edit log for it. collection_selection is the one to do this.
collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {})

in new.html.erb, it's easier,
here:
object: is the log model
method: is the log model's attribute: part_number_id
collection: log's part_number_id is choose from Product model
value_method: the value displayed in select & option tag is Product's id
text_method: the text valude displayed in select & option tag is Product's part number
options{:include_blank => 'Please Select'}: when no option is available, display 'Please select' in the select & option tag.

in edit.html.erb, not only do i need to show all available products in dropdown list, also I need to select the part number of that specified log:
in the options, we added one more, :selected => @selected_log, the variable @selected_log was defined in controller/logs_controller.rb
# GET /logs/1/edit
  def edit
    @log = Log.find(params[:id])
    @selected_log = Product.find(@log.part_number_id).id
  end
it tells that the selected option is the one defined ass @selected_log.

No comments: