How to route from a nested resource in rails? Getting 'ActiveRecord::RecordNotFound in UsersController#show'

白昼怎懂夜的黑 提交于 2019-12-07 15:13:28

Just to elaborate on @Marek Lipka answer. If you run rake routes in your terminal you can see your route is something like:

/users/:user_id/mines/:id => mines#show

So in your controller when you are doing params[:id] it's looking for mines id and not users id. So in your method you should have

def find_user
  @user = User.find(params[:user_id]) #this will give you the user with id 0
end

Also noticed a couple of things you are doing wrong in your show action, since you have find_user as a before filter so you don't need to set @user again in your show action also if you want to show correct mine then your should find it with params[:id] so in your show action your code should be like:

def show
  @mine = Mine.find(params[:id]) #this will show mine with id 1 or whichever id you'll pass in url
  @tool = Tool.find(@user.tool_id)
end 

You should have:

@user = User.find(params[:user_id])

in your controller.

I couldn't change the way I found the user, because in other parts of my program, I am finding the user by using:

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

I found that specifying @ user in my link_to out of the game-state solved the issue:

<%= link_to "Home", user_path(@user), id: 'link-to-hq' %>

takes me to

/users/0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!