Rails/JS按钮onclick可以重新渲染部分图像,而无需进入数据库 [英] Rails/JS button onclick to re-render partial without entering into DB
问题描述
我希望使用按钮(添加)重新加载部分表单.我是新手,不知道如何多次单击添加"按钮来简单地在列表之类的部分显示字段.我找不到相关的示例.当对象保存在数据库中时,所有AJAX示例都提到js.erb.
I wish to reload a partial-form with a button(Add). I'm new and don't know how to simply display fields in partial like listings one under the other as many times Add button is clicked. I can't find a relevant example. all AJAX examples mention js.erb when object is saved in DB.
<div class="panel-body">
<%= render partial: "degrees/form", :locals => { :f => f } %>
<%= f.link_to (fa_icon 'plus').to_s + " Add Another Qualification ", render(:partial => 'degrees/form', :locals => { :f => f }), class: "btn btn-primary" %>
</div>
在这里,@application是试图显示学位字段的主要形式.部分是两个文本字段,一个用于选择教育程度,第二个用于详细说明.这是部分
Here, @application is the main form trying to display degree fields. Partial is simply two text-fields- one for selecting educational degree and second its detail.Here's partial
<%= f.fields_for [Degree.new], :url => { :action => "index" } do |ff| %>
<div class = "form-group" }>
<%= ff.select :level, options_for_select(Job::EDUCATION, params[:level]), include_blank: "Select Degree", class: 'span-2' %>
<%= ff.text_field :description, :class => 'span5' %>
</div>
<% ff.submit "Add Another Degree", class: 'btn btn-primary' %>
推荐答案
您不必保存要传递给.js.erb
的东西...您只需实例化...
You don't necessary need to save things to pass away to .js.erb
... you can just instantiate...
但是,如果您的示例是精确的,则将丢失链接的remote: true
标志...并且链接上未定义partial ...您需要创建一个视图以响应ajax ...
But if your example is precise, you are missing the remote: true
flag for the link... And the partial is not defined on the link... you need to make a view responding to the ajax...
表格示例
<div class="panel-body">
<%= link_to new_thing_path, remote: true do %>
<i class="fa fa-plus">
Add another qualification
<% end %>
<div class="new-things-container">
</div>
</div>
控制器回答ajax请求
Controller answering to the ajax request
class ThingsController < ApplicationController
def new
@thing = Thing.new
respond_with @thing
end
end
查看ajax请求,以在指定的div中呈现部分视图
View for the ajax request rendering a partial inside a specified div
//views/things/new.js.erb
$('.panel-body .new-things-controller').append("<%= render partial: 'degrees/form', locals: { thing: @thing } %>")
这篇关于Rails/JS按钮onclick可以重新渲染部分图像,而无需进入数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!