Reputation:
Why does this link_to method redirect to my root path?
Users controller:
def show
@user = User.find(params[:id])
@user.comments.build
@comment = Comment.new
@user.votes.build
@vote = Vote.new
end
def vote:
@comment = Comment.find(params[:id])
Vote.create!(voteable_id: params[:id], voteable_type: 'Comments')
@user = User.find(params[:id])
redirect_to @user
end
Users view:
<%= link_to "vote", vote_comment_path(:id => comment.id), method: :post, :class=> "btn %>
Routes.rb:
post 'comments/:id/vote' => 'comments#vote', as: 'vote_comment'
resources :users do
resources :comments
resources :ratings
resources :votes
end
I was expecting clicking on vote to redirect back to the user, but instead it goes to my home page.
Can I not use params[:id]
twice under the same method?
Upvotes: 1
Views: 555
Reputation: 6682
When you call
vote_comment_path(:id => comment.id)
it passes comment.id
into the method, which is retrieved as params[:id]
.
If the value of params[:id]
is comment.id
, then:
def vote
# ...
@user = User.find(params[:id]) # look up user by comment.id - BAD!
redirect_to @user # wrong user!
end
You are looking up a user by a comment ID, not a user ID.
If the current user is User 1 but the comment is Comment 5, you are being redirected to User 5, the user with the same ID as the comment.
I'm guessing there is some authorization check dumping you back to root (eg. not allowed to view User 5 while logged in as User 1). Check your logs to see where the redirect took place.
This might be related, but the proper way to build is like this:
def show
@user = User.find(params[:id])
@comment = @user.comments.build
@vote = @user.votes.build
end
Upvotes: 1