My app has a select box for users to choose a "venue". This select box is, as you would expect, in a form. I also have an action somewhere on the page that creates a new venue via AJAX. After the new venue is created, I would like to updated the venue select box to reflect this.
My solution was to put the select box in a partial and render the partial from the create action in the controller.
<div id="venue_select" style="clear: both;">
<%= render :partial => 'venue/venue_select_box' %>
</div>
The partial looks like this:
<%= f.collection_select :venue_id, @user_venues, :id, :name, :prompt => 'Select a venue' %>
where f is the form reference:
<% form_for :shows do |f| %>
The problem is that f is undefined in the partial, so I get an error. One solution would be to include the entire form, but I feel like that should not be necessary because I am not updating the entire form. Any ideas on how to go about this?
These are all great options but I think I found the easiest. Basically, I just hard coded the name in the collection_select so I would not need the "f" variable:
<%= collection_select 'shows[venue_id]', :venue_id, @user_venues, :id, :name, { :prompt => 'Select one of your previous venues' } %>
Then my VenueController is as follows:
class VenueController < ApplicationController
layout 'main'
before_filter :login_required, :get_user
def create
begin
venue = @user.venues.create(params[:venue])
@user_venues = @user.venues
render :partial => 'venue_select_box', :success => true, :status => :ok
rescue ActiveRecord::RecordInvalid => invalid
flash[:errors] = invalid.record.errors
render :text => '', :success => false, :status => :unprocessable_entity
end
end
end
If this method is bad practice for any reason, please let me know and I will happily credit you for the answer.