1
我有一个对象通过bridge-object ContactSector联系has_many个扇区。我在联系人索引页上有一个表单,我现在用简单的字符串过滤联系人列表。Rails:用另一个对象(has_many到)过滤对象列表
我想有一个复选框列表的部门,@contacts只返回与选定的扇区的联系人列表。它不必匹配所有的人,至少一个。
模式
class Contact < ActiveRecord::Base
include Filterable
scope :firstname, -> (firstname) { where("firstname like ?", "#{firstname}%")}
scope :lastname, -> (lastname) { where("lastname like ?", "#{lastname}%")}
scope :title, -> (title) { where("title like ?", "#{title}%")}
scope :sectors, -> (sector) {where("sector like ?", "#{sector}%")} #Attempt
has_many :sectors, through: :contact_sectors
has_many :contact_sectors
accepts_nested_attributes_for :sectors
end
class ContactSector < ActiveRecord::Base
belongs_to :contact
belongs_to :sector
end
class Sector < ActiveRecord::Base
has_many :contacts, :through => :contact_sectors
has_many :contact_sectors
end
filterable.rb
module Filterable
extend ActiveSupport::Concern
module ClassMethods
def filter(filtering_params)
results = self.where(nil)
filtering_params.each do |key, value|
results = results.public_send(key, value) if value.present?
end
results
end
end
end
查看
<%= form_tag '', :method => :get do %>
<label>Sectors</label><br>
<% Sector.all.each do |sector| %>
<%= hidden_field_tag 'sector_ids[]', '' %>
<%= check_box_tag 'sector_ids[]', sector.id %>
<%= sector.sector %>
<% end %>
<% end %>
控制器
def index
@contacts = Contact.filter(params.slice(:firstname, sector_ids: [])
end