DataMapper:解決関連クラスの作成時、idはnil
2186 ワード
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
#
関連クラスのオブジェクトを作成するときに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
#