简体   繁体   中英

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. I have a link on my events form that calls a (twitter bootstrap) modal that contains the venue form. 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. 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

  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:

$('#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

<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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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