Rails 4: How to update a collection_select based on another collection_select through AJAX?

后端 未结 2 1590
Happy的楠姐
Happy的楠姐 2021-01-01 02:24

The problem: I need to filter a collection of Units based upon the selection of a collection of Organizations.

Upo

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-01 02:52

    Instead of placing an duplicate organization_id on the projects table you should set the relationship up to go through the Unit model.

    class Organization < ActiveRecord::Base
      has_many :units
      has_many :projects, through: :units
    end
    
    class Unit < ActiveRecord::Base
      belongs_to :organization
      has_many :projects
    end
    
    class Project < ActiveRecord::Base
      belongs_to :unit
      has_one :organizaton, through: :unit
    end
    

    This avoids the awkward issue where you have to ensure that a unit and a project have the same organizaton_id.

    This also means that you no longer need a input to select the organization when creating a Project - just the unit.

提交回复
热议问题