Calling custom controller method from view on click and then updating view in Ruby on Rails 4

I’ve been looking into AJAX recently and trying to apply it to my Rails app. I’m having trouble understanding how to call a custom controller method from the view and then updating the view.

I’ve attempted to add a helper_method to a controller where I update the attribute I need. However, I’m not sure how to call this method from the view, and if I do, how I re-render a partial affected by that change. Does replace_html fit in here?


Here’s a concrete explanation of what I’m looking for, if my explanation wasn’t clear:

Currently, I am defining @question in the GamesController show method, and then doing this in the view:

<%= link_to 'Next Question', @question, remote: 'true', :class=> "btn" %>

I have the QuestionsController responding to :html and :js. Then, I render what I need to in the following file and update the “#question-show” div in games/show.html.erb

$('#question-show').html("<%= escape_javascript(render 'question') %>");

The questions/_question.html.erb partial contains info on that particular question.

This works fine right now. However, I have multiple question per game, and I want the <%= link_to 'Next Question', @question, remote: 'true', :class=>
btn" %>
in games/show.html.erb to first update what @question is. I have this now in GamesController, but it’s not linked to my view:

def next_question
    @game.progress += 1
    @question = Question.find(@game.questions[@game.progress])
    respond_to do |format|
      format.json { head :no_content }
helper_method :next_question

After I update what @question is, I want to re-render the #question-show div with the updated question.


Anyways, thanks for your time! First time posting on Stack Overflow, so please let me know if there’s something wrong with my submission. I’ve spent a while looking at similar questions, but haven’t had any luck. Thank you!

Source: ajax

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.