简体   繁体   English

如何在 Rails 应用程序中实现虚 URL?

[英]How can I implement vanity URL's in a Rails application?

I want users to able to have a profile page at site.com/myNameHere.我希望用户能够在 site.com/myNameHere 上拥有个人资料页面。 Rails looks for a controller named "myNameHere." Rails 查找名为“myNameHere”的控制器。 Is it possible to setup routes.rb so that if the controller is not found, "myNameHere" gets sent as a parameter to another controller?是否可以设置 routes.rb 以便如果未找到控制器,“myNameHere”将作为参数发送到另一个控制器?

You can add a route like this:您可以添加这样的路线:

map.profile_link '/:username', :controller => 'profiles', :action => 'show'

Be sure to add it low enough in the file, below your resources, that it doesn't interfere with other routes.确保将它添加到文件中足够低的位置,在您的资源下方,以免干扰其他路由。 It should be lowest priority.它应该是最低优先级。 Next, you need to change your show action to use a username instead of id:接下来,您需要更改 show 操作以使用用户名而不是 id:

def show
  @user = User.find_by_username(params[:username])
end

That's all there is to it.这里的所有都是它的。 Happy coding!快乐编码!

UPDATE:更新:

I've expanded this answer into a full blog post, Vanity URLs in Ruby on Rails Routes .我已将此答案扩展为完整的博客文章, Ruby on Rails Routes 中的虚名 URL I have additional code samples and a more thorough explanation.我有额外的代码示例和更详尽的解释。

Just thought I would update this for Rails 3. I have a field 'website' in my user model that is going to act as the vanity route, and I am going to route to a static page for each vanity route.只是想我会为 Rails 3 更新这个。我的用户模型中有一个字段“网站”,它将充当虚荣路由,我将路由到每个虚荣路由的静态页面。 I want to display all of a users 'events' if the vanity route is called.如果调用虚荣路线,我想显示所有用户的“事件”。

#config/routes.rb
  get '/:website', :controller => 'static_pages', :action => 'vanity'

#app/controllers/static_pages_controller.rb
  def vanity
      @user = User.find_by_website(params[:website])
    if @user != nil #in case someone puts in a bogus url I redirect to root
      @events = @user.events
    else
      redirect_to :root
    end
  end

#app/views/static_pages/vanity.html.erb
<h1><%= @user.website  %> events</h1>

<table>
  <tr>
    <th>Title</th>
    <th>Starts at</th>
    <th>Description</th>
    <th></th>
    <th></th>
    <th></th>
  </tr>

<% @events.each do |event| %>
  <tr>
    <td><%= event.title %></td>
    <td><%= event.starts_at %></td>
    <td><%= event.description %></td>
  </tr>
<% end %>
</table>

I think this is a good alternative if you don't want to use a gem.如果您不想使用 gem,我认为这是一个不错的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM