1

我试图安装 gem FriendlyId。我正在关注 railscast:314-pretty-urls-with-friendlyid。它似乎很容易安装。但不为我工作。

以下是我执行的步骤:

added gem "friendly_id", "~> 4.0.9" in Gemfile

然后我运行bundle install命令

然后将我的产品模型修改为:

class Product < ActiveRecord::Base
  extend FriendlyId
  friendly_id :name

  attr_accessible :name, :product_code, :recipe, :selling_price, :servings,   letsrate_rateable "quality", "packaging", "hygiene" , "service", "price"
  validates :name, :presence => true
  class << self
    def search(params)
             if params[:search]
                products = Product.published.includes(:product_sub_categories)
             end
    end
  end
 end

它仍然显示'id':

http://localhost:3000/products/9

根据 railscasts 它应该显示产品名称。但事实并非如此。我单独安装 gem 但没有效果。

谁能告诉我我错过了什么?

4

1 回答 1

0

Not sure why this is not mentioned in Guide, but try:

alias_attribute :to_param, :slug

This works because to_param method allows to customise the id part of URL. And here you are assigning that part to friendly_id generated URL.

Another solution

I am not sure if this is implemented inside friendly_id, but I did this:

class Product < ActiveRecord::Base
  def self.find(id_or_slug)
    case id_or_slug
    when String
      find_by_slug id_or_slug
    else
      super id_or_slug
    end
  end
end
于 2013-08-30T15:52:33.733 回答