Chained select box in Rails 3

ε祈祈猫儿з 提交于 2020-01-14 05:49:21

问题


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 appear showing B and C and if I select B another select box would appear showing D.

Thank you very much.


回答1:


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.



来源:https://stackoverflow.com/questions/5302470/chained-select-box-in-rails-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!