Skip to content

Instantly share code, notes, and snippets.

@marcocarvalho
Created June 25, 2011 17:38
Show Gist options
  • Save marcocarvalho/1046694 to your computer and use it in GitHub Desktop.
Save marcocarvalho/1046694 to your computer and use it in GitHub Desktop.
Rails 3 FormBuilder Select Helper that deals with association
#
# ~/app/helpers/combo_helper.rb
#
# Association => { { id: 1, association: "Coolest" } , { id: 2, association: "Hardest" } }
#
# Model Class << ActiveRecord::Base
# has_many :associations
# end
#
# Use:
#
# <%= form_for model do |f| %>
# <%= f.select_from_association :association, [accept normal select options] %>
# <% end %>
#
# Output
# <select name="model[association]" id="model_association">
# <option id="1">Coolest</option>
# <option id="2">Hardest</option>
# </select>
#
module CombosHelper
def select_from_association(model,assoc, options = {} )
collection = options_for_select(model.class.reflect_on_association(assoc).klass.all.map { |m| [m.send(assoc), m.id] }, model.send(assoc.to_s+'_id') )
select(model.class.to_s.parameterize, assoc.to_s+"_id", collection, options)
end
module FormBuilder
def select_from_association(assoc, options = {})
@template.select_from_association(@object, assoc, options)
end
end
end
ActionView::Helpers::FormBuilder.send(:include, CombosHelper::FormBuilder)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment