require 'rubygems' require 'data_mapper' DataMapper.setup :default, "mysql://root:123456@localhost/cc" class Url include DataMapper::Resource property :id, Serial property :original, String,:length => 255 belongs_to :link end class Link include DataMapper::Resource property :id, Serial property :identifier, String property :created_at, Date has 1, :url has n, :visits end class Visit include DataMapper::Resource property :id, Serial property :created_at, Date property :ip, String property :contry, String belongs_to :link end DataMapper.auto_migrate! DataMapper.finalize url = Url.create(:original => "http://") p url
?
#<Url @id=nil @original="http://" @link_id=nil>
?
在创建关联类的对象时,没有进行save的时候,@id的值正常就是nil,但是有些时候需要它有值
解决办法是在belongs_to后面加上,:required => false
?
require 'rubygems' require 'data_mapper' DataMapper.setup :default, "mysql://root:123456@localhost/cc" class Url include DataMapper::Resource property :id, Serial property :original, String,:length => 255 belongs_to :link,:required => false end class Link include DataMapper::Resource property :id, Serial property :identifier, String property :created_at, Date has 1, :url has n, :visits end class Visit include DataMapper::Resource property :id, Serial property :created_at, Date property :ip, String property :contry, String belongs_to :link,:required => false end DataMapper.auto_migrate! DataMapper.finalize url = Url.create(:original => "http://") p url
?#<Url @id=1 @original="http://" @link_id=nil>
?