-
-
Save solnic/557430 to your computer and use it in GitHub Desktop.
| require 'active_record' | |
| require 'dm-core' | |
| require 'dm-mysql-adapter' | |
| require 'dm-migrations' | |
| require 'dm-validations' | |
| DataMapper.setup :default, "mysql://localhost/tests" | |
| module DM | |
| class Group | |
| include DataMapper::Resource | |
| storage_names[:default] = "groups" | |
| property :id, Serial | |
| property :name, String | |
| has n, :students | |
| end | |
| class Student | |
| include DataMapper::Resource | |
| storage_names[:default] = "students" | |
| property :id, Serial | |
| property :name, String | |
| belongs_to :group | |
| end | |
| end | |
| DataMapper.auto_migrate! | |
| ActiveRecord::Base.establish_connection :adapter => "mysql", :database => "tests" | |
| module AR | |
| class Group < ActiveRecord::Base | |
| set_table_name "groups" | |
| has_many :students | |
| end | |
| class Student < ActiveRecord::Base | |
| set_table_name "students" | |
| belongs_to :group | |
| end | |
| end | |
| ar_student = AR::Student.create :group_id => 'foo' | |
| dm_student = DM::Student.create :group_id => 'foo' | |
| puts "ar_student errors: #{ar_student.errors.inspect}" # => {} | |
| puts "dm_student errors: #{dm_student.errors.inspect}" # => #<DataMapper::Validations::ValidationErrors:0x8df30d8 @resource=#<DM::Student @id=nil @name=nil @group_id="foo">, @errors={:group_id=>["Group must be an integer"]}> |
OSIM!
At the minimum, I think AR could reflect the fact that it's an integer column and the value does not look anything like an Integer. As it is I think it just called #to_i on the value passed in, and uses whatever that returns. I never liked that idiom, and DM instead does a regexp on the String and only if it is numeric does it call #to_i on it.
I have heard though that AR will do some reflection on the DB and setup some basic validations, like uniqueness, presence, and a few others. The main problem they're going to run into with this approach is that constraints aren't consistent across DBs, and they aren't quite as rich as what you can describe in ruby within a model. Overall I think it's a better approach than doing nothing, but IMHO it still isn't as good as specifying the model as authoritative and deriving everything from it.
True dat.
with AR3 it stores group_id as 0 :)