简体   繁体   中英

How do I add/remove values to a collection_select (Drop-Down List) in Rails?

I am looking some some guidance on how to add and remove values to my drop down lists.

Here is my code I am using in my View/Project/_form.html.erb

<div class="control-group">
 <%= vf.label(:category_id, :class => "control-label") %>
 <div class="controls">
 <%= vf.collection_select :category_id, Category.all, :id, :name, prompt: true %>
 </div>
</div>

It is retrieving a list of values that I provided in my seeds.rb

Is there a good way in Rails to add some sort of "new Value" selection that will allow me to then enter some text and save it to the Drop Down list?

Now I don't want to add some extra static value in the code. This would be more for the user to be able enter an additional value in the form while using the application.

I am guessing this will involve some sort of JQUERY Dialog Box and an AJAX call but I was hopeing to get lucky.

Either way, any kind of assistance or examples would be greatly appreciated.

I would add a secondary form to the page, along the lines of this:

form_for @category, remote: true, :url => {:action => "add_category"} do |f|
  f.text_field :category_name
  f.submit "Add category"

In your controller, you would handle the remote form and render a javascript template to update your select boxes. Something like:

def add_category
  Category.create(category_params)
  respond_to do |format|
    format.js
  end
end

And then you'll have an add_category.js view:

$(".controls").html("<%= j (render 'category_selects') %>");

Lastly, you need to create the 'category_selects' partial to update the select values:

<%= collection_select :category_id, Category.all, :id, :name, prompt: true %>

If you haven't yet, I recommend reading through the "Working with JavaScript" rails guide: http://edgeguides.rubyonrails.org/working_with_javascript_in_rails.html

Hope this helps!

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