user3100151 user3100151 - 4 months ago 10
Ruby Question

Undefined new_record? Ruby Rails

I am trying to check if the domain host url record exist in the domain table before creating it again, but I am getting this error:

undefined method `new_record?' for #<Domain::ActiveRecord_Relation:0x007f320ed8af80>


The class GetMeta is a service object that is getting initialize when a user enter a URL in a form and click submit. I am taking the URL from the form and calling MetaInspector with it to get more meta informations.

The first part (if) new_record method is working perfectly fine, but is creating duplicate values in the domain table. I tried to create a conditional logic, but I am having this bug that I don't know how to fixed.

class GetMeta
include ActiveModel::Model

def initialize(url)
@url = url
end

def new_record

page = MetaInspector.new(@url)
@domain = Domain.where(:host => page.host)

if new_record?
Domain.create! do |url|
url.root_url = page.root_url
url.scheme = page.scheme
url.host = page.host

url.links.build(url: page.url, title: page.best_title, description: page.description)
end
else
Link.create! do |link|
link.url = page.url
link.title = page.best_title
link.description = page.description
end
end
end

private

def new_record?
@domain.new_record?
end

end

Answer

The problem is described by an error. Let's see:

undefined method `new_record?' for
#<Domain::ActiveRecord_Relation:0x007f320ed8af80>

The problem is the line @domain = Domain.where(:host => page.host)

This returns an ActiveRecord relation instead of single record. You should take a .first or .last.

@domain = Domain.where(:host => page.host).last

That's the fix, but let's see how can we improve the code.

We can use method exists? which is defined in ActiveRecord Relation (docs: http://api.rubyonrails.org/classes/ActiveRecord/FinderMethods.html#method-i-exists-3F)

if Domain.exists?(host: page.host)
  Link.create! do |link|
    link.url = page.url
    link.title = page.best_title
    link.description = page.description
  end
else
  Domain.create! do |url|
    url.root_url = page.root_url
    url.scheme = page.scheme
    url.host = page.host

    url.links.build(url: page.url, title: page.best_title, description: page.description)
  end
end

This way we don't need instance variable @domain and helper method new_record?

Comments