我有关于rails 的friendly_id 的红色文档。这很容易:您将某个属性设置为 slug。
example.com/username
User has_one profile
Profile belongs_to User
所以你看到了我的困境。我在配置文件模型中没有列用户名。如何链接用户模型、用户名字段,以便我可以使用友好 ID 执行 example.com/username?
当然,这相对简单。
我有关于rails 的friendly_id 的红色文档。这很容易:您将某个属性设置为 slug。
example.com/username
User has_one profile
Profile belongs_to User
所以你看到了我的困境。我在配置文件模型中没有列用户名。如何链接用户模型、用户名字段,以便我可以使用友好 ID 执行 example.com/username?
当然,这相对简单。
您可以在路由文件的末尾使用“catch-all”路由:
map.connect ':username', :controller => 'profiles', :action => 'show' (this is for Rails 2.3)
在配置文件控制器中,方法显示您检查是否有具有该用户名的用户,以及它是否属于当前配置文件
def show
if User.find_by_username(params[:username])
if @current_user == User.find_by_username(params[:username])
# @profile = @current_user.profile
# render projects#show view
else
# flash error message, because the current user tries to access other users profile (in case your app doesn't allow it)
else
# render page not found error
end
end
对于项目模型,我有类似的情况,来自 projects/id => /project_name。在您的情况下会更容易一些,因为在数据库中您有唯一的用户名。啊,不涉及额外的宝石。
在你的ProfilesController#show
:
def show
@user = User.joins(:profile).where("profiles.username = ?", params[:username])
end
路线:
match ':username' => "profiles#show'
或者,您可以向您的用户模型添加一个方法以使您的控制器更清洁:
class User < ActiveRecord::Base
def fetch_by_username(username)
joins(:profile).where("profiles.username = ?", username)
end
end
在你的控制器中:
@user = User.fetch_by_username(params[:username])
您可以使用自定义方法生成所需的 slug。
class Profile < ActiveRecord::Base
has_many :users
has_friendly_id :custom_url_method, :use => :slugged
def custom_url_method
self.user.username.to_url
end
to_url 来自 Stringex gem。您也可以使用 Friendly_id 本身提供的 Babosa 的辅助方法之一。