在Rails中使用simple_form和AJAX解析JSON错误 [英] Parsing JSON errors using simple_form and AJAX in rails
问题描述
我有一个在用户仪表板上使用简单表单"和remote => true的表单(由仪表板视图和仪表板控制器处理).该表格允许用户添加自定义游戏规则;但是,它是通过Jquery的.load()函数加载表单的.表单是从规则"视图(由规则控制器处理)加载的.
I have a form that is using Simple Forms and remote => true on the users dashboard (which is handled by a dashboard view and dashboard controller). The form allows a user to add a custom game rule; however, it's loading the form via a Jquery's .load() function. The form is loading from the "rules" view (handled by a rules controller).
当用户单击提交"按钮时,我没有得到任何错误验证.
When the user clicks the submit button, I'm not getting any error validation.
这是规则控制器上的create动作:
Her is the create action on the rule controller:
def create
@rule = Rule.new(params[:rule])
respond_to do |format|
if @rule.save
format.html { redirect_to dashboard_path, notice: 'Rule was successfully created.' }
format.json { render json: @rule, status: :created, location: @rule }
format.js
else
format.html { render template: 'dashboard/index'}
format.json { render json: @rule.errors, status: :unprocessable_entity }
format.js
end
end
end
我的views文件夹中有一个名为create.js.erb的js文件,该文件当前为空.我认为我必须以某种方式解析此create.js.erb文件中的JSON错误数据,但是我不知道该怎么做.
I've got a js file called create.js.erb in my views folder that is currently empty. I think that I have to somehow parse the JSON error data in this create.js.erb file, but I have no idea how to do it.
此外,仪表板视图/控制器正在调用此表单,但是规则控制器正在处理该表单吗?
Also, does it matter that this form is being called by the Dashboard view/controller but the form is being handled by the Rule controller?
推荐答案
在create.js.erb中尝试以下操作
Try the following inside create.js.erb
$('.error-messages').remove();
<% if @rule.errors.any? %>
$('body').append('<ul class="error-messages"></ul>');
<% @rule.errors.full_messages.each do |msg| %>
$('.error-messages').append('<%= escape_javascript msg %>');
<% end %>
<% end %>
这会将错误附加在您的body标签中.
This will append the errors in your body tag.
这篇关于在Rails中使用simple_form和AJAX解析JSON错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!