Ruby on rails:从 id 到名称/标题等的 URL [英] Ruby on rails: URL from ids to names/titles etc

查看:34
本文介绍了Ruby on rails:从 id 到名称/标题等的 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从生成脚手架创建了模型对象,但现在我想而不是链接到
/:controller/:id (/objectname/1) 到/:controller/:title (/objectname/new_blog_post).我该怎么做才能使链接更正指向标题而不是 ID 的链接?

I created model objects of from generating a scaffold, but now I want to instead of linking to
/:controller/:id (/objectname/1) to /:controller/:title (/objectname/new_blog_post). How do I do this so that links will correct link to the title and not id?

我想从:

/:controller/:id 

/:controller/:name 

推荐答案

用于参数

class User < ActiveRecord::Base

  def to_param
    name.blank? ? id : name
  end

end

或者查看插件,acts_as_sluggable 和friendly_id 是我所知道的.

Or look into a plugin, acts_as_sluggable and friendly_id are ones I know of.

哦,是的,如上所述,请确保您使用的任何内容都是独一无二的.

Oh yes and as mentioned make sure whatever you use is unique.

它会像这样工作:

class UsersController < ActionController::Base

  def index
    @users = User.all
  end

end

在视图中:

<% @users.each do |user| %>
  <%= link_to user.name, user_path(@user.id) %>
<% end %>

如果那个用户的名字是 John 那么它会在你点击那个链接后呈现/users/John

And if the that users name is John then it will render /users/John after you click that link

这篇关于Ruby on rails:从 id 到名称/标题等的 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆