ruby on rails - Why root route not working with users#show? -


i tried root route root 'users#show' user taken profile upon logging in, instead i'm confronted error:

activerecord::recordnotfound in userscontroller#show couldn't find user 'id'=  @user = user.find(params[:id]) 

when use profile own tab via, <li><%= link_to "profile", current_user %></li> works, can't put root 'current_user' or error:

argumenterror missing :action key on routes definition, please check routes. root 'current_user' 

thank time.

actually, error message you've provided points problem.

if have root defined you've mentioned root "users#show" executes show action of userscontroller, if have action implemented "the standard way":

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

it fails here, because there no params[:id]. value fetched url. if you're pointing url:

localhost:3000/users/1 

the params[:id] has value "1".

because you're trying point root_path:

localhost:3000 

there no param :id bound, thus:

user.find(params[:id]) 

throws exception.

if want have "the proper way", modify config/routes.rb:

root "users#profile" "profile" => "users#profile" 

and inn usercontroller:

class usercontroller < applicationcontroller   # ...   def profile     @user = current_user # or other logic relevant fetching logged in user   end end 

assuming have current_user method implemented, , returns proper user

however, have aware - setting "profile" root cause non-logged in users see error page.

hope helps!

update - moving template partial

you can extract code need app/views/users/show.html.erb. let's say, it's content like:

<h3><%= @user.name %></h3> <small><%= @user.bio %></small> 

you can extract partial app/views/users/_user_details.html.erb, has content:

<h3><%= user.name %></h3> <small><%= user.bio %></small> 

please note, @ removed here, , in app/views/users/show.html.erb, can delete code replace with:

<%= render partial: "user_details", locals: { user: @user } %> 

the same might used in app/views/pages/home.hmtl.erb like:

<% if logged_in? %>   <%= render partial: "user_details", locals: { user: @user } %> <% end %> 

assuming, in pagescontroller have like:

class pagescontroller < applicationcontroller   def home     @user = current_user   end end 

Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -