开发者

How to have example.com/username instead of example.com/user/1 in Rails 3?

How can I amend the routing from http://localhost:3000/profiles/1 to http://localhost:3000/myusername ?

I have a Profile model with the following table:

def self.开发者_如何学编程up
    create_table :profiles do |t|
      t.string :username
      t.text :interest

      t.timestamps
    end
 end

And my routes.rb file:

  resources :profiles

I have looked at similar answers dealing with to_param, devise or nested loops or even an example in Rails 2.3, but i couldn't find a way that works.

What changes should I make to the profile/view/show.html.erb, routes.rb and model/profile.rb (if any) to amend the routing from http://localhost:3000/profiles/1 to http://localhost:3000/username? I'm learning from the basics, hence I rather not use any gems or plugins.


If you want use usernames instead of IDs try friendly_id gem.

If you want to do it by yourself, the easiest way is to override method to_param in our model to return username, and then search in your controller by username.

In model:

def to_param
  username
end

In controller:

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

In routes.rb file:

  match '/:id' => 'profiles#show'


This is what you need http://apidock.com/rails/ActiveRecord/Base/to_param

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜