Rails路由/名称而不是/ users /:id

时间:2016-10-19 10:17:14

标签: ruby-on-rails

我已经完成了Hartl的教程,并尝试以与twitter相同的方式为我的推文克隆创建虚荣URL,例如www.twitter.com/realDonaldTrump

我设法让我的网址看起来像/ users /:slug。 想知道 - 我如何得到它只是/:slug?

这是我到目前为止所做的事情:

1.在我的用户模型中,'用户名'没有列,所以我使用了' name'代替。

2.生成新的迁移以向用户模型DB添加slug列。

3.插入rails控制台,输入以下内容为所有用户添加slugs:

User.all.each do |user|
  user.slug = user.name.downcase.parameterize
  user.save
end

4.Configured UsersController显示动作:

def show
  @user = User.find_by_slug(params[:id])
  @microposts = @user.microposts.paginate(page: params[:page])
  redirect_to root_url and return unless @user.activated?
end

现在我已对其进行了配置,以便显示/ users /:slug,如何更改它以便它只是/:slug?

3 个答案:

答案 0 :(得分:1)

使用

更改您的根目录
func textFieldHandler(textField: UITextField!)
    {
        if (textField) != nil {
            textField.text = "Filename"
        }
    }

和您的UsersController

get '/:slug', to: 'users#show'

不要忘记删除':show' before_action:set_user,仅限:[:show,:edit,:update] 你的Controller作为“set_user”使用:id而不是:slug来检索实例

请注意,保存时必须担心模型中的slug唯一性

def show
  @user = User.find_by slug: params[:slug]
...
end

答案 1 :(得分:1)

Try this ......

edit app/models/user.rb

class User < ActiveRecord::Base
  extend FriendlyId
  friendly_id :name, use: :slugged
end

User.create! name: "Username"

Change User.find to User.friendly.find in your controller

User.friendly.find(params[:id])

rails server

http://localhost:3000/users/username

If you're adding FriendlyId to an existing app and need to generate slugs for existing users, do this from the console, runner, or add a Rake task:

User.find_each(&:save)

To get /username instead of /users/username try this ...

In your User model add

class User < ActiveRecord::Base
  ...
  def to_param
    name
  end
  ...
end

But make sure in your controller you then find users by their name.

In your controller add

class UsersController < ApplicationController
  ...
  def show
    @user = User.find_by(name: params[:id])
  end
end

As for routing your users to /username, you have several options:

get ':id', to: 'users#show', as: 'show'
resources 'users', path: '/'

Just make sure you put these routes at the end of your routes file.

Hope this will work for you.

答案 2 :(得分:0)

get '/:slug', to: 'users#show'将此作为最后一条路线并检查。

由于它是我们创建的命名路线,它应该在最后,因此其他路线不会受到干扰。

Users Controller

def show
  @user = User.find_by slug: params[:slug]
end