Dynamically adding items to a select list in Ruby On Rails using Ajax
I have looked at a whole bunch of solutions for this and maybe I am just dense, but I can't get anything to work. These are the two selects I am trying to tie together in a prod开发者_Go百科uct/new view that will allow the user to select a category of product and then constrain the subcategory listing:
<p>
<%= f.label :category_id %>:
<%= f.select("category", Category.find(:all).collect {|c|[c.name, c.id]})%>
</p>
<p>
<%= f.label :subcategory_id %>:
<%= f.select("subcategory", Subcategory.find(:all).collect {|s|[s.name, s.id]})%>
</p>
I have a function in my subcategory controller to get the information from the database:
def get_subcategories
@subcategories = Subcategory.find_by_category_id(:all)
end
But I can't figure out how to wire it together, and it seems like it should be easy in RoR.
Well it's not completely trivial but it is achievable with a little effort. The basic approach would be:
- Populate the category select list when the view is initially rendered
- Add a javascript handler to be triggered when this is changed
- Do an AJAX call to the server within this handler and call your
get_subcategories
method within a controller action - Have the controller action respond with the values for populating the subcategory select list
- Have the AJAX response handler update the HTML for the subcategory select list
- In the case where you want the category select list to be populated with a default value when the form is initially rendered you will want to have the AJAX call automatically made at that time, even before the user has selected anything.
For example, in JQuery you could put this together with the following methods
.change()
sets up the handler on the select list.triggerEvent('change')
would cause the event to fire after load (if you need that)$.getJSON()
can be used to fetch and parse the AJAX response.remove()
and.append()
can be used to clear and update the subcategory select with the result
精彩评论