sent-hil
sent-hil

Reputation: 19285

undefined method `parameterize' for nil:NilClass

I've been trying to do SEO friendly urls, and managed to get it work, but when I call index action on blogs, I get a weird "undefined method `parameterize' for nil:NilClass." The method works when using show method.

  #model
  def to_s
    title
  end

  def to_param
    "#{id}-#{to_s.parameterize}"
  end

  #controller
  @blogs = Blog.find.all

Screenshot of error http://www.freeimagehosting.net/image.php?83e76a260b.png

Upvotes: 1

Views: 3917

Answers (2)

joshneipp
joshneipp

Reputation: 91

In case anyone is having trouble with this in Rails 5....I left out the #to_s part, which is critical.

class Post < ApplicationRecord

  def to_param
    slug
  end

  def slug
    "#{id}-#{pretty_url}"
  end

  def pretty_url
    title.to_s.parameterize
  end

end

Upvotes: 1

sent-hil
sent-hil

Reputation: 19285

Turns out you can't call title.parameterize on to_param without error. So I added a permalink column and called parameterize on that.

#models/blog.rb
before_save :permalink

def to_param
 "#{id}-#{permalink}"
end

def permalink
 self.permalink = self.title.parameterize
end

And voila. I knew it was something really stupid.

Upvotes: 7

Related Questions