【发布时间】:2016-09-02 02:03:58
【问题描述】:
所以,我有一个有很多问题的事件模型。关系与 Post->Comment 中的关系相同。我尝试为问题实现一些 Ajax,但似乎我遗漏了一些东西,因为 View 在不刷新页面的情况下不会更新。删除方法也有同样的问题。
这是我的 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
这就是它在 Events show.haml 中的样子:
%section#question_section
%h1 Questions:
#questions
= render @event.questions
#question-form
%h1 Submit a question:
= render 'questions/form'
并创建.js.erb 文件:
$('#questions').append("<%= j render partial: @question %>");
$('#question_content').val('');
我尝试了几个不同的教程,但总是遇到同样的问题。仅在刷新后查看更新。这也是我在 Stackoverflow 上的第二篇文章,如果有任何问题,我将不胜感激。
编辑 1:大部分时间我一直在学习本教程:https://pragmaticstudio.com/blog/2015/3/18/rails-jquery-ajax
编辑 2:create.js.erb 似乎没有响应,尝试使用警报或控制台日志对其进行测试,但没有任何成功。在控制台中触发一个按钮后:“由 QuestionsController#create as JS 处理”(因此它运行一个正确的文件,但文件本身不执行任何代码)。不知道为什么会这样。
【问题讨论】:
-
你能确认 create.js.erb 确实被执行了吗?并且你的问题有内容。 (即它不只是附加空的
h4标签,看起来它根本没有附加) -
似乎没有,我尝试控制台记录一些文本,但在触发创建按钮后它没有出现。也很累:format.js {render action: "create"} in controller
-
您的服务器控制台有错误吗?服务器响应说它呈现了什么?
-
它说:由 QuestionsController#create as JS 处理,然后一些事务(插入、选择、更新)没有错误。
-
哦,并且:渲染问题/_question.haml (0.4ms) 在布局/应用程序中渲染问题/create.js.erb
标签: ruby-on-rails ajax nested-resources