rails 4、不刷新页面不更新嵌套资源,使用Ajax
rails 4, nested resource doesn't updates without page refreshing, using Ajax
所以,我有 has_many 个问题的事件模型。关系与 Post->Comment 中的相同。我已经尝试为问题实施一些 Ajax,但似乎我遗漏了一些东西,因为视图在不刷新页面的情况下不会更新。删除方法也有同样的问题。
这是我的 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
问题_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.haml:
%h4
= question.content
这是它在活动中的样子 show.haml:
%section#question_section
%h1 Questions:
#questions
= render @event.questions
#question-form
%h1 Submit a question:
= render 'questions/form'
和create.js.erb文件:
$('#questions').append("<%= j render partial: @question %>");
$('#question_content').val('');
我试过几个不同的教程,但总是遇到同样的问题。仅在刷新后查看更新。这也是我在 Whosebug 上的第二个 post,如果有任何问题,我将不胜感激。
编辑 1:大部分时间我一直在关注本教程:https://pragmaticstudio.com/blog/2015/3/18/rails-jquery-ajax
编辑 2:create.js.erb 似乎没有响应,尝试使用警报或控制台日志对其进行测试,但没有成功。在控制台中触发一个按钮后:"Processing by QuestionsController#create as JS"(因此它运行一个正确的文件,但文件本身不执行任何代码)。不知道为什么会这样。
所以问题出在 HAML 上。必须将控制器中的 format.js 行更改为:
formta.js { render layout: false }
这是帮助解决这个问题的帖子:Rails update.js.erb not executing javascript
所以,我有 has_many 个问题的事件模型。关系与 Post->Comment 中的相同。我已经尝试为问题实施一些 Ajax,但似乎我遗漏了一些东西,因为视图在不刷新页面的情况下不会更新。删除方法也有同样的问题。
这是我的 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
问题_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.haml:
%h4
= question.content
这是它在活动中的样子 show.haml:
%section#question_section
%h1 Questions:
#questions
= render @event.questions
#question-form
%h1 Submit a question:
= render 'questions/form'
和create.js.erb文件:
$('#questions').append("<%= j render partial: @question %>");
$('#question_content').val('');
我试过几个不同的教程,但总是遇到同样的问题。仅在刷新后查看更新。这也是我在 Whosebug 上的第二个 post,如果有任何问题,我将不胜感激。
编辑 1:大部分时间我一直在关注本教程:https://pragmaticstudio.com/blog/2015/3/18/rails-jquery-ajax
编辑 2:create.js.erb 似乎没有响应,尝试使用警报或控制台日志对其进行测试,但没有成功。在控制台中触发一个按钮后:"Processing by QuestionsController#create as JS"(因此它运行一个正确的文件,但文件本身不执行任何代码)。不知道为什么会这样。
所以问题出在 HAML 上。必须将控制器中的 format.js 行更改为:
formta.js { render layout: false }
这是帮助解决这个问题的帖子:Rails update.js.erb not executing javascript