Rails 3.1 依赖/级联下拉菜单 [英] Rails 3.1 Dependent / Cascading Dropdowns

查看:58
本文介绍了Rails 3.1 依赖/级联下拉菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在掌握 Rails 3.1,我希望有人能指出 Gem 的方向,这将允许我在表单上使用依赖选择(或指出如何在 Rails 3.1 中最好地完成此操作).我遇到过chained_selects插件,不过好像依赖prototype,所以在3.1中不太理想.

I am getting to grips with Rails 3.1, and I am hoping that someone can point me in the direction of a Gem that will allow me to use dependent selects on a form (or indicate how this is best done in Rails 3.1). I have come across the chained_selects plugin, but that seems to rely on prototype, so it is not ideal in 3.1.

最简单的例子是汽车品牌/型号:

The simplest example of this is car makes/models:

我有 3 个模型:车辆制造、车辆模型和车辆修剪.我还有赋值表 VehicleMake_vehicleModel 和 VehicleModel_vehicleTrim,它们指定了适合每个品牌的车型等.

I have 3 models: vehicleMake, vehicleModel and vehicleTrim. I also have assignment tables vehicleMake_vehicleModel and vehicleModel_vehicleTrim, which specify what models are appropriate for each make etc.

我有一个车辆模型,我想用品牌、模型和装饰填充它.车辆模型属于车辆制造商、车辆型号和车辆修剪.

I have a vehicle model which I am trying to populate with a make, model and trim. The vehicle model belongs_to vehicleMake, vehicleModel and vehicleTrim.

如何确保模型的下拉列表仅显示所选品牌(以及修剪)的模型?第二点,我如何在我的车辆模型中验证这一点?

How can I ensure that the dropdown for model only shows models for the make that is selected (and thus for trim)? As a second point, how can I validate this in my vehicle model?

谢谢!

推荐答案

我不知道有任何 jQuery 插件能做到这一点.但实际上这只是一系列 Ajax 调用.

I don't know of any jQuery plugins that do that off the top of my head. But really it's just a series of Ajax calls.

当从 Make 下拉列表中选择一个选项时,您将其发送到服务器(通过 Ajax),取回关联的模型,并用这些选项填充下一个下拉列表.然后重复修剪.

When an option is selected from the Make drop down, you send that to the server (via Ajax), get the associated Models back, and populate the next drop down with those options. Then repeat for Trim.

至于验证,您可能希望使用 validates_inclusion_of 或只是手动编写:

As for validation, you'll probably want to use validates_inclusion_of or just write it manually:

validate :model_matches_make?

def model_matches_make?
  unless Make_Model.where(make: self.make).map(&:model).includes?(self.model)
    errors.add(:make, "is not valid for your model") 
  end
end

(在那里使用地图感觉不对,所以也许有更好的方法)

(using map feels wrong there so maybe there's a better way)

这篇关于Rails 3.1 依赖/级联下拉菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆