你可以用这种方式重构你的代码:
域类
class Domain < ActiveRecord::Base
has_many :links
end
链接类
class Link < ActiveRecord::Base
belongs_to :domain
validates :href,
:uniqueness => true
attr :domain_url
def domain_url=(main_domain_url)
self.domain = Domain.where(domain: main_domain_url).first ||
Domain.new(domain: main_domain_url)
end
def domain_url
self.domain.nil? ? '' : self.domain.domain_url
end
end
用法
Link.create(href: 'example.com/somepage',
text: 'Some Page',
domain_url: 'example.com')
结论
在这两种情况下(你的和我的)你都会收到两个请求(就像这样):
Domain Load (1.0ms) SELECT "domains".* FROM "domains" WHERE "domains"."domain" = 'example.com' LIMIT 1
AREL (0.1ms) INSERT INTO "links" ("href", "text", "domain_id", "created_at", "updated_at") VALUES ('example.com/somepage', 'Some Page', 5, '2011-04-26 08:51:20.373523', '2011-04-26 08:51:20.373523')
但使用此代码,您还可以免受未知域的侵害,因此 Link 会自动创建一个。
您还可以使用验证唯一性,以便删除所有 unless Link.exists?(:href => '...')。