2

Would this be considered bad practice?

unless Link.exists?(:href => 'example.com/somepage')
  Domain.where(:domain => 'example.com').first.links.create(:href => 'example.com/somepage', :text => 'Some Page')
end

I realize I might be requesting more data then I actually need, can I optimize this somehow?

Domain is a unique index so the lookup should be fairly quick.

Running Rails 3.0.7

tereško
  • 58,060
  • 25
  • 98
  • 150
Marco
  • 4,345
  • 6
  • 43
  • 77

2 Answers2

3

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 => '...').

Viacheslav Molokov
  • 2,534
  • 21
  • 20
2
Domain.where(:domain => 'example.com').
  first.links.
  find_or_create_by_href_and_text(:href => 'example.com/somepage', :text => "Some Page")

UPD

@domain = Domain.where(:domain => 'example.com').
            first.links.
            find_or_create_by_href('example.com/somepage')
@domain.text = "My Text"
@domain.save

Or you can use extended update_or_create_by_* method:

Domain.update_or_create_by_href('example.com/somepage') do |domain|
  domain.text = "My Text"
end

More info here:

find_or_create_by in Rails 3 and updating for creating records

Community
  • 1
  • 1
fl00r
  • 82,987
  • 33
  • 217
  • 237
  • Wouldn't that find_or_create match against both the href AND the text? If I remove the _and_text it would only match against the href, correct? – Marco Apr 26 '11 at 19:39
  • Sorry, not sure I follow.. I need to be able to add the :text, but I only want to match against the :href – Marco Apr 26 '11 at 19:47