Reputation: 1215
So right now, I have a rails app that opens up a modal window with the article title on it. I was trying to allow users to click on the right arrow on the modal window which will move onto the next article by fetching the next article from the model. Does anyone have any ideas on how to do this in the best way possible? How do you fetch the prompt object in the view, update it and display it again on the view?
EDIT: This is sorta random idea, but can you just make an ajax call with the dummy data which calls a function in the controller which retrieves the next post and render the page with that data? Is there a better way?
Upvotes: 1
Views: 39
Reputation: 6571
I was trying to allow users to click on the right arrow on the modal window which will move onto the next article by fetching the next article from the model.
Based on this sentence, your thinking seems to be that the order of operations will be this:
But it doesn't have to be in this order. In fact, the most straight-forward (and in my opinion, elegant) way to do this is to find the next and previous articles inside your controller's show method at the time the original article is requested, and embed their links into the arrows in the modal. That way, when the page for Article 5 loads, the arrows will already be pointing to Article 4 and Article 6. So the order would be:
For example, let's assume that id numbers in the articles table also denote their position in relation to each other. In real life this is unlikely to be the case, but for simplicity's sake we can assume it:
def show
@article = Article.find(params[:id])
# at this time, also find next and previous
@next = Article.find(params[:id] + 1)
@previous = Article.find(params[:id] - 1)
end
Then, in your show.html.erb:
<%= link_to "Next", articles_path(@next) %>
<%= link_to "Previous", articles_path(@previous) %>
Of course, instead of having a "next" text for the link, you'd be wrapping the links around the next and previous arrows in your modal. So it might be like this instead:
<%= link_to articles_path(@next) do %>
<img src="nextarrow.png">
<% end %>
You get the idea. You can also do this with AJAX by adding remote: true
to the link_to
method. If you do that, instead of having the whole page reload, you can have just the modal dialog contents reload, and update the links for the arrows.
There are other ways to do this too. For example, if this app will be used heavily and there's a chance that the order of articles will change while the user is viewing one of them, then that may call for a more dynamic request-response implementation, whereby you send the current article id and either "next" or "prev" to the app, and then the app first finds the next or previous article and then renders the show template with it.
Upvotes: 1