user700996
user700996

Reputation: 483

Ruby on Rails Adding New Pages to Existing Model

I have a model view controller set up for a Users table. However, the default only gives me 1 user specific page per user (users/1). However, I need another user specific page for each user (users/1/profile)? I googled really hard and couldn't find any resources on how to create it. How do you go about creating this? Thanks!

Upvotes: 0

Views: 2952

Answers (3)

Rekha Benada
Rekha Benada

Reputation: 9

You need to create a default profile page first and then create a association between profile page record and user using session id of each user

def profile
@user = User.find(session[:user_id])
end

whatever data will be associated with user will show here and you need to connect database table record with user to test whether it is showing that record or not.

Upvotes: 1

Keith Hanson
Keith Hanson

Reputation: 133

You can find the full details to do this in a Restful way here: http://guides.rubyonrails.org/routing.html#adding-more-restful-actions

This is, imho, better than providing a match route because you are able to use the named routes the restful route generates. Another option would be to just provide a named route instead of the restful route, but sticking with the "Rails" way of doing this will provide less headaches down the road when you might need to refactor.

Here's the code in particular that you would want to use:

#Routes
resources :users do
  member :profile
end

#Controller Action
def profile
   @user = User.find(params[:id])
end

#View link
<% @users.each do |user| %>
  <%= link_to "Profile", profile_user_path(user) %>
<% end %>

Upvotes: 2

Gazler
Gazler

Reputation: 84150

You would add a new route to your config/routes.rb

 match "users/:id/profile" => "users#profile"

Then your matching controller action and view.

Your controller may look like

def profile
    @user = User.find(params[:id])
end

And your view would be in views/users/profile.html.erb

Upvotes: 1

Related Questions