Chained select box in Rails 3
I have a table related with itself:
id | data | owner_id
1 | A | null
2 | B | 1
3 | C | 1
4 | D | 2
So therefore B and C belong to A and D belongs to B.
My question is how can I display in a Rails 3 view a chained select box where if you select a "data" then another select box appears with its "children" and when you select one of the children another select box appears with its children and so forth using Ajax?
For example in the previous table if I select A in the select box another select box would a开发者_如何学JAVAppear showing B and C and if I select B another select box would appear showing D.
Thank you very much.
There are 2 ways you could approach this
- Ajax
Add an onchange event to your first field which would call a method in your controller to fetch the relevant options and populate the second select menu.
Just learned that there's a plugin called ChainSelects that attempts to do this. You could try it out. (I would prefer to do it myself, but its up to you.)
- Javascript
There's a Railscast that explains this technique in detail. Even though this railscast uses Rails 2.3 you can use the technique and customize it for Rails 3.
精彩评论