[Rails] initialization of new model objects in Rails
Hey guys... having an issue that hopefully someone can help with.
I have a ActiveRecord model called WebPage, it has two fields - url and title. I want the title to be determined by parsing the html (I'm using Nokogiri) - and this is where I'm having issues.
My code looks something like:
class WebPage < ActiveRecord::Base
attr_accessible :url, :title, :doc
def doc
@doc ||= Nokogiri::HTML(open(@url))
end
def title
title = @doc.css('title')
end
end
What is happening, is if I run this and try and create a new object (@page = WebPage.new(@url), I get:
ActionView::Template::Error (undefined method `css' for nil:NilClass)
Now, if I set @doc in my controller, and change the name of title to set_title and call @page.title = @page.set_title, it works. But that is very ugly and if I've learned anything from rails, is that if it looks ugly to start with, it's probably not the right way.
What am I doing wrong?
-- You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msg/rubyonrails-talk/-/_ClYnRd3ej0J.
For more options, visit https://groups.google.com/groups/opt_out.
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home