Created
October 31, 2012 02:50
-
-
Save jtroxel/3984528 to your computer and use it in GitHub Desktop.
An example Module mixing in re-usable Rails associations.
This file contains 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 CategoryGroup | |
module ClassMethods | |
# Set up the association and accepts_nested_attributes_for in the client object. Also defines some accessor and helper | |
# methods based on the name parameter | |
def category_group_association(name, group) | |
has_many "#{name}_categorizations".to_sym, :class_name => "Categorization", :foreign_key => "categorizable_id", | |
:conditions => ["categorizations.categorizable_group = ? and categorizations.categorizable_type = ?", group, "#{self.name}"] | |
has_many "#{name}_categories".to_sym, :through => "#{name}_categorizations".to_sym, :source => :category | |
attr_accessible "#{name}_categorizations_attributes".to_sym | |
accepts_nested_attributes_for "#{name}_categorizations".to_sym, :allow_destroy => true, :reject_if => proc { |attributes| | |
attributes['category_id'].blank? && attributes['id'].blank? # This says ignore if a new record (no id) and no category selected | |
} | |
# META ALERT!!! | |
# Set up methods using the name parameter | |
module_eval <<-"end_eval", __FILE__, __LINE__ | |
def has_#{name}_categories? | |
p #{name}_categories | |
#{name}_categories.present? && #{name}_categories.any? | |
end | |
def primary_#{name}_category | |
primary_#{name}_cz.present? && primary_#{name}_cz.category | |
end | |
def primary_#{name}_cz | |
#{name}_categorizations.any? && #{name}_categorizations.primary.first | |
end | |
end_eval | |
end | |
end | |
def self.included(base) | |
base.extend ClassMethods | |
end | |
def association_for_category_group(name) | |
send("#{name}_categorization") | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment