简体   繁体   English

rails 4,使用Ajax,不刷新页面就不会更新嵌套资源

[英]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. 关系与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. 我试图实现一些Ajax for Questions,但似乎缺少了一些东西,因为View不会在不刷新页面的情况下进行更新。 The same problem with delete method. 与删除方法相同的问题。

Here's my question_controller.rb: 这是我的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: 问题_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: 问题_question.haml部分:

%h4
    = question.content

This is how it looks in Events show.haml: 这是在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: 和create.js.erb文件:

$('#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. 这也是我在Stackoverflow上发表的第二篇文章,因此,如果出现问题,将不胜感激。

EDIT 1 : mostly I've been following this tutorial: https://pragmaticstudio.com/blog/2015/3/18/rails-jquery-ajax 编辑1 :大多数情况下,我一直在关注本教程: 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. 编辑2 :create.js.erb似乎没有响应,试图通过警报或控制台日志对其进行测试,但未成功。 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). 在控制台中触发具有以下内容的按钮后:“通过QuestionsController#create as JS处理”(因此它运行适当的文件,但文件本身不执行任何代码)。 Have no idea why that happening. 不知道为什么会这样。

So the problem was because of HAML. 因此问题出在HAML。 Had to change my format.js line in the controller to: 必须将控制器中的format.js行更改为:

formta.js { render layout: false }

Here's the thread that helped to solve this: Rails update.js.erb not executing javascript 这是帮助解决此问题的线程: Rails update.js.erb不执行javascript

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM