Skip to content

Commit

Permalink
add basic support for many_to_many (if you want :through support)
Browse files Browse the repository at this point in the history
  • Loading branch information
jackdempsey committed Dec 7, 2008
1 parent 3759bc8 commit 872e1ae
Showing 1 changed file with 17 additions and 4 deletions.
21 changes: 17 additions & 4 deletions lib/sequel_polymorphic/sequel_polymorphic.rb
Expand Up @@ -50,11 +50,12 @@ def _#{able}=(#{able})
alias :belongs_to :many_to_one alias :belongs_to :many_to_one


def one_to_many(*args, &block) def one_to_many(*args, &block)
one_to_many_variable, options = *args many_of_class, options = *args
many_class = one_to_many_variable.to_s.singularize options ||= {}
many_class = many_of_class.to_s.singularize
if able = options[:as] if able = options[:as]
method_definitions = %{ method_definitions = %{
associate(:one_to_many, :#{one_to_many_variable}, :key=>:#{able}_id) do |ds| associate(:one_to_many, :#{many_of_class}, :key=>:#{able}_id) do |ds|
ds.filter(:#{able}_type=>'#{self}') ds.filter(:#{able}_type=>'#{self}')
end end
Expand All @@ -70,7 +71,7 @@ def _remove_#{many_class}(#{many_class})
#{many_class}.#{able}_type = nil #{many_class}.#{able}_type = nil
#{many_class}.save #{many_class}.save
end end
def _remove_all_#{one_to_many_variable} def _remove_all_#{many_of_class}
#{many_class.capitalize}.filter(:#{able}_id=>pk, :#{able}_type=>'#{self}').update(:#{able}_id=>nil, :#{able}_type=>nil) #{many_class.capitalize}.filter(:#{able}_id=>pk, :#{able}_type=>'#{self}').update(:#{able}_id=>nil, :#{able}_type=>nil)
end end
} }
Expand All @@ -82,6 +83,18 @@ def _remove_all_#{one_to_many_variable}


alias :has_many :one_to_many alias :has_many :one_to_many


def many_to_many(*args, &block)
many_to_class, options = *args
options ||= {}
if through = options[:through] and able = options[:as]
#many_to_many :tags, :through => :taggings, :as => :taggable
associate(:many_to_many, many_to_class,
:left_key => "#{able}_id".to_sym,
:join_table => through) { |ds| ds.filter("#{able}_type".to_sym=>self.class.to_s) }
else
associate(:many_to_many, *args, &block)
end
end
end # ClassMethods end # ClassMethods
end # Polymorphic end # Polymorphic
end # Plugins end # Plugins
Expand Down

0 comments on commit 872e1ae

Please sign in to comment.