好的朋友我几天都在努力解决这个问题,我现在完全感到困惑。
我正在运行Rails 5和Ruby 2.3.0 根据我对ROR的理解,如果我加载这样的网址
post/3-DIY-Mirror
ActiveRecord能够通过对字符串执行to_i来解释post id,并且只留下整数3(即帖子的id)。 现在我明白了FriendlyId可以通过Post.friendly.find(params [:id])来覆盖那种行为并让ActiveRecord找到没有整数3的DIY镜像 我已经遵循了几套说明,最终得到了两种行为,而不是我认为FriendlyId想要给我的行为。
案例1 在我的控制器中,我有:
def show
@page = Page.find(params[:id])
if request.path != page_path(@page)
redirect_to @page, status: :moved_permanently
end
end
在我的模型中我有:
class Page < ApplicationRecord
extend FriendlyId
friendly_id :name, use: [:slugged, :finders, :history]
validates :name, :slug, presence: true
def to_param
[id, name.parameterize].join("-")
end
def should_generate_new_friendly_id?
send(friendly_id_config.slug_column).nil? &&
!send(friendly_id_config.base).nil?
end
end
这会返回一个类似http://localhost:3000/pages/4-sdfasdf的网址,并且可以正常运行。但是,默认的ActiveRecord Behavior就是字符串开头的id。
案例2 现在,如果我把我的控制器带到:
def show
@page = Page.friendly.find(params[:id])
if request.path != page_path(@page)
redirect_to @page, status: :moved_permanently
end
end
和我的模特:
class Page < ApplicationRecord
extend FriendlyId
friendly_id :name, use: [:slugged, :finders, :history]
validates :name, :slug, presence: true
end
我在没有id的情况下得到它并且它有效,但是URL有空格而不是连字符?! http://localhost:3000/pages/asdf asdfas asdfas
我已经关注了github上的几个指南而没有生成http://localhost:3000/pages/asdf-asdfas-asdfas。它们产生上述结果之一。任何人都可以发现任何光线,因为我确信我已经正确设置了所有内容,但它似乎并没有自动显示破折号。