我有一份表格是部分问卷,如果选择了某些答案,表格会显示其他问题。我需要存储这些问题的答案,并且可能允许人们改变他们的答案,我更愿意在一个地方做决策a)和b)在Rails中,所以我有一个表格可以检查我的@assessment
对象,根据@assessment
对象的状态显示或隐藏各种问题。
我一直试图了解如何使用AJAX来设置往返旅程。我的表单是部分的,所以我可以在@assessment
对象更新时重新加载它。我见过的大多数示例都涉及提交表单,并使用POST操作将params传递给Rails对象,然后使用JavaScript重新渲染部分。我试图通过单击按钮上的单选按钮来实现,但无法确定我是如何从那里获得新更新的@assessment
对象的。
我该怎么办?是否足够痛苦,我应该尝试更好的方法?
这是一个简化形式partial,_ form.html.haml:
= bootstrap_form_for @assessment, as: :put, url: project_assessment_path(@project), remote: :true do |f|
.panel.panel-default
.panel-heading
.panel-title Lorem ipsum dolor sit amet
.panel-body
= answer_question_1(@project)
- if show_question(@assessment, :question_2)
.panel.panel-default
.panel-heading
.panel-title Lorem ipsum dolor sit amet?
.panel-body
= f.radio_button :question_2, true, label: "Yes", inline: true, remote: :true
= f.radio_button :question_2, false, label: "No", inline: true, remote: :true
- if show_question(@assessment, :question_3)
.panel.panel-default
.panel-heading
.panel-title Lorem ipsum dolor sit amet?
.panel-body
= f.radio_button :question_3, true, label: "Yes", inline: true, remote: :true
= f.radio_button :question_3, false, label: "No", inline: true, remote: :true
...
- if @assessment.complete?
- case @assessment.assessment_message
- when :not_applicable
.panel.panel-success.hidden
.panel-body.alert-success
Duis scelerisque id ipsum et consectetur.
- when :low
.panel.panel-success.hidden
.panel-body.alert-success
Duis scelerisque id ipsum et consectetur.
- when :medium
.panel.panel-warning
.panel-body.alert-warning
Duis scelerisque id ipsum et consectetur.
- when :high
.panel.panel-info.hidden
.panel-body.alert-info
Additional information is required:
- if @assessment.form_required?
.panel.panel-success
.panel-heading
.panel-title Description of Work
.panel-body
= f.text_area :aims_hypothesis, label: "Aims/Hypothesis", rows: 4
= f.text_area :methodology, label: "Brief Description of Methodology", rows: 4
= f.text_area :significance, rows: 4
...
= f.form_group do
= f.submit "Save"
这包含在edit.html.haml中的div中(因为@assessment是自动创建的,截止日期为止,没有new
操作)
.row
#assessment-form.col-xs-12.col-md-11
= render partial: "form"
这里是assessment_controller.rb的相关部分:
before_action :find_project
before_action :find_assessment
before_action :authorised?
def next_question
@assessment.update_attributes(strong_parameters)
respond_to do |format|
format :html { redirect_to sign_in_path }
format :js do
render partial: "update_assessments"
end
end
end
和_update_assessments.js.coffee:
$('#assessment-form').html("<%= escape_javascript (render partial: 'form') %>")
答案 0 :(得分:1)
我认为你的概念是有效的,是的,你应该使用AJAX。
只需将onChange Handler添加到单选按钮并启动AJAX-Post
即可$(document).on('change', '.your-class-or-id-of-the-radio', function() {
var element = $(this); // if you need some data from radio button
$.ajax({
type: 'POST',
url: '/path/to/your/controller',
data: {data: 'you need to pass'}
});
});
如果您需要更多详细信息,请询问。