How to redirect to the same object position after update

Asked

Viewed 38 times

0

I am displaying a collection of random objects in my index action. However the objects are displayed one at a time. So:

@objects = Object.order("RANDOM()").limit(1)

In the index view, I can send a comment to this object, only when I send the comment, it updates the page and because it is random it displays a new object.

The question is, how do I redirect in the create comment action to this same object, to view what was commented?

1 answer

0

Well, I didn’t quite understand the logic of showing only 1 in index, it would be more interesting to use the show of the item in question.

But anyway, to your question. Go to the controller comentario, in the way create of it you will see a redirect_to after a if, which checks whether the comentario was saved. Change which page you want it to redirect as soon as the comentário, since you probably have a relationship between objeto and comentario, informing the id of objeto. It would look something like this:

def create
    ...
    if @comment.save
        redirect_to objects_path(object_id: @comment.object_id)
    else
    ...
end

And in your method index of controller object

if params[:object_id]
    @objects = Object.where(id: params[:object_id])
else
    @objects = Object.order("RANDOM()").limit(1)
end

Again, that’s kind of ugly, that’s for sure. The ideal would be for you to use the show, to show only 1, when calling the method index, you would call the show, with this random value. E no redirect_to of the create de Comment, you would pass :

object_path(@comment.object_id)

instead of

objects_path(object_id: @comment.object_id)
  • Thanks man, it worked. I also agree with you, but in this particular case we don’t even have an action show. But it worked perfectly your solution. Thank you.

  • Denada, mark the answer as solved.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.