简体   繁体   English

Rails Ajax Form添加新的关联记录

[英]Rails Ajax Form to add new associated record

I have an events form that has a select drop down for venues. 我有一个活动表单,其中有一个针对场所的下拉列表。 Currently if a new venue is to be added for an event users have to navigate away to the venue form, create their venue and then navigate back to the events form, which is less than ideal. 当前,如果要为事件添加新场所,则用户不得不导航到场所表单,创建其场所,然后导航回事件表单,这不理想。

I've half got this working via AJAX but it's not quite there. 我已经通过AJAX进行了这项工作,但还不足够。 I have a link on my events form that calls a (twitter bootstrap) modal that contains the venue form. 我的事件表单上有一个链接,该链接调用包含场所表单的(Twitter Bootstrap)模式。 The venue form has been set to :remote => true and on submit it does create a new venue but the modal/form does not close and the event form's venue select isn't refreshed. 场所表单已设置为:remote => true并且在提交时确实创建了一个新场所,但模式/表单未关闭,并且事件表单的场所选择未刷新。 I have to manually refresh to page to confirm the new venue is added. 我必须手动刷新到页面以确认已添加新场所。

The VenueController create actions looks like this, with the respond to calling format.js VenueController创建动作如下所示,并带有对format.js的响应

  def create
    session[:return_to] ||= request.referer
    @venue = Venue.new(params[:venue])

    respond_to do |format|
      if @venue.save
        format.js
      else
        format.html { render :action => "new" }
      end
    end
  end

In app/views/venues I have create.js.erb which looks like this: 在app / views / venue中,我有一个create.js.erb,看起来像这样:

$('#townvenue').html("<%= escape_javascript(render(@town_venue)) %>");

(I'm almost certain this is where i'm going wrong). (我几乎可以确定这是我要去的地方)。

#townvenue is a div within my event form and itself a partial located in app/views/events/_town_venue.html.erb #townvenue是我的活动表单中的一个div,它本身是位于app / views / events / _town_venue.html.erb中的部分

<div id="townvenue">
<div>
  <%= f.label :town_id, :class => 'control-label form_labels' %>
  <%= f.collection_select :town_id, Town.order(:town), :id, :town, include_blank: true %>
</div>

<div>
  <%= f.label :venue_id, "Venue", :class => 'control-label form_labels' %>
  <%= f.grouped_collection_select :venue_id, Town.order(:town), :venues, :town, :id, :name, include_blank: true %><br /><a href="#myModal" role="button" data-toggle="modal">[Add new venue]</a><br />
</div>
</div>

Can anyone help with the final pieces in this puzzle please? 任何人都可以帮助解决这个难题的最后部分吗?

This is just a hint. 这只是一个提示。 Get your select id and append to it your new venue with $('#select_box_id').append('<option value="<%= venue.value %>"><%= venue.name %></option>') in your .js.erb file. 获取您的选择ID,并使用$('#select_box_id').append('<option value="<%= venue.value %>"><%= venue.name %></option>')放在您的.js.erb文件中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM