使用friendly_id 匹配单个Rails 路由中的多个模型
我有一个 Company 和一个 User 模型,两者都带有一个通过friendly_id 的 slug.确保两个模型中的 Slug 都是唯一的.
I have a Company and a User model, both with a slug via friendly_id. Slugs are ensured to be unique across both models.
我想要网址:
http://www.example.com/any_company_name
http://www.example.com/any_user_name
例如/apple
和 /tim
我不确定如何在 Rails 中实现这一点.
I'm not sure how to achieve this in Rails.
我尝试了以下各种排列:
I have tried various permutations of:
routes.rb:
resources :users, path: ''
resources :companies, path: ''
get '*search', to: 'my_controller#redirect'
和
my_controller#redirect:
@company = Company.friendly.find(params[:search])
redirect_to @company if @company
@user = User.friendly.find(params[:search])
redirect_to @user if @user
但是我无法让它工作.我可以让 /apple
重定向到 /companies/apple
和 /tim
重定向到 /users/tim
(通过删除 path: ''
选项)但这不是我想要实现的.
However I can't get it to work. I can get /apple
to redirect to /companies/apple
and /tim
to redirect to /users/tim
(by removing the path: ''
option) but this is not what I want to achieve.
我遇到了类似的问题,并且能够通过创建具有 slug 属性和与Sluggable"类的多态关联的 PublicSlug 模型来解决它.我还使用了一个 Sluggable 问题,我将其包含在我想查询的模型中.
I had a similar problem and was able to solve it by creating a PublicSlug model with a slug attribute and a polymorphic association to a "Sluggable" class. I also used a Sluggable concern that I included in models I would like to query.
PublicSlug 模型
The PublicSlug model
class PublicSlug < ActiveRecord::Base
extend FriendlyId
friendly_id :sluggable_name, use: :slugged
belongs_to :sluggable, polymorphic: true
private
# Generate the slug based on the title of the Sluggable class
def sluggable_name
sluggable.name
end
end
懒惰的关注
module Sluggable
extend ActiveSupport::Concern
included do
has_one :public_slug, dependent: :destroy, as: :sluggable
delegate :slug, to: :public_slug
end
end
公司和用户模型.
class User < ActiveRecord::Base
include Sluggable
end
class Company < ActiveRecord::Base
include Sluggable
end
我现在可以使用
Sluggable.friendly.find(slug).sluggable
重定向可以在您的控制器中处理如下:
The redirect could be handled in your controller as follows:
def redirect
@sluggable = Sluggable.friendly.find(params[:search]).sluggable
redirect_to @sluggable
end