新手问题 请问对多对都,里面代参数是如何进行查询的?

QueXuQ · 2013年06月27日 · 最后由 jasli2 回复于 2013年06月28日 · 2418 次阅读

我想做一个这样的东西:

公司
客户

这两个 model,但是他们间是多对多的,是就是一个公司有多个客户,一个客户可以有多个公司。 但是里面涉及一个是否交易的 boolean,就是公司与客户直接交易是否结束。

所有有 3 个 model

Company
Customer
CompanyCustomership

正常情况查找 Company 下的 Customer,就是Company.first.customers,通过客户找公司就相反,但是我里面加了一个 deal 的 boolean 到 CompanyCustomership。请问我怎么查 Company 下,deal 为 true 的 Customer 呢? 我只知道可以通过 CompanyCustomership 来查找出来,例如CompanyCustomership.where(deal: true, company_id: xx).customers

google 过,但是输入关键词“rails column many_to_many”找不到,在 guides 里没有看到讲这个的,英文不好伤不起。

Company.joins(:company_customships).where('company_customships.deal' => true, id: xx)

我是瞎拼凑出来的...

#1 楼 @blacktulip 试了一下,这样可以找到 deal 为 true 的,company 为 xx 的,但是后面就接不到 customers。 如果company_customships里加别的参数就要变得这么复杂?不可以像 Company.customers,这样那么方便?

#2 楼 @QueXuQ 可以呀,写个 private method 不就好了,把复杂的部分藏起来,留接口在外面

has_many  :deal_customers, through: :company_customships, 
          class_name: "Customer", 
          source: :customer, 
          conditions => ['company_customships.deal = ?',true]

首先,你的两个 model 肯定有这样的代码: Company.rb

has_many :company_customership
has_many :customer, :through => :company_customership

我的做法是,添加以下代码:

has_many :company_checked_customership, :class_name => "CompanyCustomership", :conditions => { :checked => true }
has_many :checked_customers, :through => :company_checked_customership, :source => :curstomer

这样,你就可以使用Company.first.checked_customers 来 refer 已经 check 过的客户了。

希望能帮到你。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号