Created
January 28, 2010 11:23
-
-
Save slaskis/288632 to your computer and use it in GitHub Desktop.
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 DataMapper | |
module Model | |
module Relationship | |
alias_method :orig_has, :has | |
# Overrides has method if: | |
# 1. It's ManyToMany | |
# 2. Share the same storage | |
# | |
# And then modify the table to save the relationship ids in a string instead of | |
# a A_B table. | |
# | |
# This is to avoid "ambiguous column name"-errors in DataMapper 0.10.2 | |
# | |
def has(cardinality, name, *args) | |
options = extract_options(args) | |
model = ( options[:model] || name ).to_s.singularize.to_const_string.constantize | |
if cardinality == n && options.key?( :through ) && options[:through] == Resource && self.storage_name(repository_name) == model.storage_name(repository_name) | |
# 1. Create a property | |
property :"#{name}_ids", String, :length => 65000, :default => "" | |
# 2. Create a reader | |
class_eval <<-RUBY, __FILE__, __LINE__ + 1 | |
def #{name}(query=nil) | |
@#{name} ||= #{model}.all( (query||{}).merge( :id => #{name}_ids.split(",") ) ) | |
end | |
RUBY | |
# 3. Create a hook | |
class_eval <<-RUBY, __FILE__, __LINE__ + 1 | |
before :save do | |
if @#{name} | |
self[:"#{name}_ids"] = @#{name}.map {|r| r.id }.join(",") | |
@#{name} = nil | |
end | |
end | |
RUBY | |
else | |
orig_has( cardinality , name , *args ) | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment