我司做健康类网站,需求如下:有 Movement 与 Disease 两个 model,逻辑上它们是 has_and_belongs_to_many 关系,但此外有多一层需求,需要在对应关系上加一个 status,如:有些 Movement 对 Disease 有好的影响,也可能有不好的影响,这个时候 has_and_belongs_to_many 就不太适用了,我的做法如下: Movement model:
class Movement < ActiveRecord::Base
has_many :disease_movment_restores, :class_name => "DiseaseMovement", :dependent => :destroy, :conditions => { :status => true }
has_many :restores, :through => :disease_movment_restores, :source => "disease"
has_many :disease_movment_taboos, :class_name => "DiseaseMovement", :dependent => :destroy, :conditions => { :status => false }
has_many :taboos, :through => :disease_movment_taboos, :source => "disease"
end
Disease model:
class Disease < ActiveRecord::Base
acts_as_options
end
为中间表创建模型 DiseaseMovement,它有自己的 id 字段
class DiseaseMovement < ActiveRecord::Base
set_table_name "diseases_movements"
belongs_to :disease
belongs_to :movement
end
在 Movement edit 页面中:
<div class="box">
<h3 class="hndle"><span>有助于恢复以下疾病</span></h3>
<div class="inside">
<%= f.select :restore_ids, Disease.find_as_options, {:include_blank => ""}, :class => "chzn-select-deselect", :multiple => "multiple", "data-placeholder" => "请选择疾病..." %>
</div>
</div>
<div class="box">
<h3 class="hndle"><span>疾病禁忌</span></h3>
<div class="inside">
<%= f.select :taboo_ids, Disease.find_as_options, {:include_blank => ""}, :class => "chzn-select-deselect", :multiple => "multiple", "data-placeholder" => "请选择疾病..." %>
</div>
</div>
尤其要说明一下 edit 页面中我有使用 Chosen (https://github.com/harvesthq/chosenplugin,真心好用!) 这个
关于 Disease.find_as_options 这个东西,如果记录很多很多,可能就不太适合了!
效果见下图:
保存之后数据库中间表记录如下:
一直做前端,刚上手 ROR,希望大家多多指点!