问题
I have a gameplay screen, with a link to return to a players' stat page. My test user id is 0, and the mine id is 1.
So the url of the gameplay screen is /users/0/mines/1
The button from gameplay back to player stats looks like this:
<%= link_to "Home", user_path, id: 'link-to-hq' %>
User_path seems to be correct, but when I click it, I have the error:
Couldn't find User with 'id'=1
def find_user
@user = User.find(params[:id])
end
(This is my private find user method from my user's controller.) For some reason, it's grabbing the MINES id (of 1), not the user id (of 0)!!!
The route im using is this:
user GET /users/:id(.:format) users#show
my controller looks like this:
# This is 'Headquarters', HQ...
def show
@user = User.find(params[:id])
@mine = @user.mines.first
@tool = Tool.find(@user.tool_id)
end
private
def find_user
@user = User.find(params[:id])
end
(i have a before_action :find_user :show)
Do I need to make a custom route to grab that user Id when going back to user stats from gameplay? How can I grab the correct id?
回答1:
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
回答2:
You should have:
@user = User.find(params[:user_id])
in your controller.
回答3:
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
来源:https://stackoverflow.com/questions/24737339/how-to-route-from-a-nested-resource-in-rails-getting-activerecordrecordnotfo