All pastes #106980 Raw Edit

Unnamed

public text v1 · immutable
#106980 ·published 2006-07-30 19:03 UTC
rendered paste body
  def has_many_select(object, association, options = {})
  
    choices = Module.const_get(association.to_s.classify).find(:all, options[:find]).collect{|c| [c.name, c.id]}
    
    method = association.to_s.foreign_key.pluralize
    selected_ids = object.method(association.to_s.pluralize).call.collect{|o| o.id}
    object_name = object.type.to_s.underscore
  
    html = ''
    choices.each do |o|
      o = [o, o] unless o.kind_of? Array
      checkbox_options = {}
      value = o[1]
      checkbox_options[:type] = "checkbox"
      checkbox_options[:class] = "checkbox"
      checkbox_options[:name] = "#{object_name}[#{method}][]"
      checkbox_options[:value] = value
      checkbox_options[:id] = "#{object_name}_#{method}_#{value}"
      checkbox_options[:checked] = "checked" if selected_ids.include? value
      
      html << content_tag('label', tag('input', checkbox_options) + o[0],:for => options[:id])
    end
    content_tag 'div', html, :class => 'multi_select'
  end