且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Rails 3.1 依赖/级联下拉菜单

更新时间:2023-02-01 11:51:09

我不知道有任何 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)