在Rails 3的链式选择框链式、Rails

2023-09-10 19:01:19 作者:傲气逼人

我有自己相关的表:

id | data | owner_id
1  | A    | null
2  | B    | 1
3  | C    | 1
4  | D    | 2

因此​​,因此B和C属于A和D属于B。

So therefore B and C belong to A and D belongs to B.

我的问题是我怎么能在Rails 3视图中显示一个链接的选择框,如果选择数据,然后出现另一个选择框与它的孩子,当你选择出现另一个选择框一个孩子其子等使用Ajax?

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?

例如在previous表,如果我选择一个,在选择框中将出现另一个选择框显示B和C,如果我选择B.将出现另一个选择框显示ð。

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.

非常感谢你。

推荐答案

有2种方式,你可以处理这个

There are 2 ways you could approach this

在阿贾克斯

添加一个onchange事件,你的第一个字段,它会调用一个方法,在您的控制器,以获取相关的选项和填充的第二选择菜单。

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.

刚刚得知,有一个名为 ChainSelects 插件,试图做到这一点。你可以尝试一下。 (我想preFER做我自己,但它给你。)

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的

有一个 Railscast 解释这项技术的细节。虽然这railscast使用Rails的2.3,您可以使用该技术,并定制了对Rails 3。

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.