How to redirect to the same position of the object after the update

0

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

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

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

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

    
asked by anonymous 06.12.2016 / 23:10

1 answer

0

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

But finally, to your question. Go to the controller of comentario , in method create of it you will see a redirect_to after a if , which verifies that comentario has been saved. Change what page you want it to redirect as soon as comentário is saved, since you probably have a relation between objeto and comentario , informing 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 of Object

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

Again, this is kind of ugly, gambiarra, let's face it. Ideally you would use show , to show only 1, at the time of calling the index method, you would call show , already with that random value. And in redirect_to of create of Comment , you would pass:

object_path(@comment.object_id)

instead of

objects_path(object_id: @comment.object_id)
    
07.12.2016 / 12:26