user3100151
user3100151

Reputation: 69

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

Upvotes: 0

Views: 468

Answers (2)

nekath
nekath

Reputation: 36

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?

Upvotes: 2

andrunix
andrunix

Reputation: 1754

You are calling an instance method from within an instance method. So you need to specify which instance you are referring to. You need to use 'self'. So instead of just calling 'new_record?', try calling self.new_record?

Upvotes: 1

Related Questions