Search code examples
ruby-on-railsajaxnested-resources

rails 4, nested resource doesn't updates without page refreshing, using Ajax


So, I'm having Events model which has_many Questions. Relation is the same as in Post->Comment. I've tried to implement some Ajax for Questions, but it seems like I'm missing something, because View doesn't updates without refreshing the page. The same problem with delete method.

Here's my question_controller.rb:

def create
 @question = @event.questions.create(question_params)
 @question.user_id = current_user.id if current_user
 if @question.save
  respond_to do |format|
    format.html { redirect_to event_path(@event) }
    format.js # render questions/create.js.erb
  end
 else
  render 'events/show'
 end
end

Question _form.haml:

= simple_form_for [@event, @event.questions.new], remote: true do |f|
 = f.input :content, label: 'Your question:', id: 'question_content'
 = f.submit class: 'submit_btn'

Question partial _question.haml:

%h4
    = question.content

This is how it looks in Events show.haml:

%section#question_section
 %h1 Questions:
  #questions
   = render @event.questions

#question-form
 %h1 Submit a question:
 = render 'questions/form'

And create.js.erb file:

$('#questions').append("<%= j render partial: @question %>");
$('#question_content').val('');

I've tried few different tutorials, but always had the same problem. View updates only after refreshment. Also it is my second post on Stackoverflow so would be grateful for any suggestions if something is wrong with it.

EDIT 1: mostly I've been following this tutorial: https://pragmaticstudio.com/blog/2015/3/18/rails-jquery-ajax

EDIT 2: create.js.erb seems not to respond, tried to test it with alerts or console log, but without any success. After triggering a button in the console having: "Processing by QuestionsController#create as JS" (so it runs a proper file, but file itself doesn't executes any code). Have no idea why that happening.


Solution

  • So the problem was because of HAML. Had to change my format.js line in the controller to:

    formta.js { render layout: false }
    

    Here's the thread that helped to solve this: Rails update.js.erb not executing javascript