Rails 3.1 Dependent / Cascading Dropdowns

2019-09-12 13:43发布

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!

1条回答
Luminary・发光体
2楼-- · 2019-09-12 14:14

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)

查看更多
登录 后发表回答