开发者

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 b开发者_开发百科logs, 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


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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜