Skip to content

Instantly share code, notes, and snippets.

@tcmacdonald
Created December 22, 2011 16:26
Show Gist options
  • Save tcmacdonald/1510885 to your computer and use it in GitHub Desktop.
Save tcmacdonald/1510885 to your computer and use it in GitHub Desktop.
Grouped Select Box for Polymorphic Associations
<%= form_for(@promotion, :html => { :multipart => true }) do |f| %>
<%= select_tag 'owner', grouped_owners_for_select %>
<% end %>
class Admin::PromotionsController < AdminController
before_filter :set_owner, :only => [:create, :update]
private
def set_owner
if owner = params[:owner]
params[:promotion][:owner_id], params[:promotion][:owner_type] = owner.split('-')
end
end
end
module Admin::PromotionsHelper
def grouped_owners_for_select
grouped_options = {
'Products' => Product.all.map(&owner_option_for_select),
'Pages' => Page.all.map(&owner_option_for_select)
}
grouped_options_for_select(grouped_options, "#{@promotion.owner_id}-#{@promotion.owner_type}")
end
def owner_option_for_select
lambda {|record| [record.title, "#{record.id}-#{record.class.name}"] }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment