Created
December 22, 2011 16:26
-
-
Save tcmacdonald/1510885 to your computer and use it in GitHub Desktop.
Grouped Select Box for Polymorphic Associations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<%= form_for(@promotion, :html => { :multipart => true }) do |f| %> | |
<%= select_tag 'owner', grouped_owners_for_select %> | |
<% end %> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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