You can refactor your code in this manner:
Domain class
class Domain < ActiveRecord::Base
has_many :links
end
Link class
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
Usage
Link.create(href: 'example.com/somepage',
text: 'Some Page',
domain_url: 'example.com')
Conclusion
In both cases (your and mine) you get two request (like so):
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')
But with this code you're also protected from unknown domains, so Link
'd create one automatically.
Also you can use validates uniqueness so you can remove all unless Link.exists?(:href => '...')
.