Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to put just a rails form element in a partial?

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?

like image 275
Tony Avatar asked Apr 07 '09 03:04

Tony


2 Answers

You can pass a variable to the partial like this:

  <%= render :partial => 'venue/venue_select_box', :locals => { :f => f } %>

For stuff like this it is always good to look at the documentation.

EDIT: To use the partial with AJAX request you'll need to "recreate" the form in your .rjs template. So in your controller you'll need to find the object again.

 def venue_select
    @venue = Venue.find(params[:id])
    respond_to do |format|
      format.html
      format.js
    end
 end

Then in your venue/venue_select.rjs file:

 form_for @venue do |f|
   page[:element].replace_html :partial => 'venue/venue_select_box', :locals => { :f => f }
 end

Where :element is the id of the select menu you want to replace. Basically you just recreate the form_for and then use that to update the select field.

like image 110
vrish88 Avatar answered Sep 27 '22 17:09

vrish88


It might be easier to add the venue to the selectbox with Javascript, as an onComplete hook on your AJAX add.

like image 23
Sarah Mei Avatar answered Sep 27 '22 18:09

Sarah Mei