Rails 3.1 依赖/级联下拉菜单

发布于 2024-11-16 18:30:17 字数 435 浏览 1 评论 0原文

我正在掌握 Rails 3.1,我希望有人能指出 Gem 的方向,它允许我在表单上使用依赖选择(或者指出如何在 Rails 3.1 中最好地完成此操作)。我遇到过 chained_selects 插件,但这似乎依赖于原型,所以它在 3.1 中并不理想。

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

我有 3 个模型:vehicleMake、vehicleModel 和vehicleTrim。我还有分配表vehicleMake_vehicleModel 和vehicleModel_vehicleTrim,它们指定哪些模型适合每个品牌等。

我有一个车辆模型,我试图用品牌、型号和装饰填充该模型。车辆模型属于vehicleMake、vehicleModel 和vehicleTrim。

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

谢谢!

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:

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?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

半衾梦 2024-11-23 18:30:17

我不知道有哪个 jQuery 插件可以在我的脑海中实现这一点。但实际上这只是一系列 Ajax 调用。

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

至于验证,您可能需要使用 validates_inclusion_of 或者手动编写:(

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

使用 map 感觉不对,所以也许有更好的方法)

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.

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.

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)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文