2016-07-18 5 views
0

簡単な質問。 私は成功なしでスコープを構築しようとしています。私はこれらのモデル関連の協会のレール範囲

class User < ActiveRecord::Base 

belongs_to :store, required: true 
has_many :visits 
has_one :company, through: :store 

end 

class Store < ActiveRecord::Base 
    belongs_to :company, required: true 
    has_many :users, dependent: :nullify 
end 

class Company < ActiveRecord::Base 
    has_many :stores, dependent: :destroy 
    has_many :users, through: :stores 
end 

class Visit < ActiveRecord::Base 
    belongs_to :user 
end 

編集

は、今私はChartkick宝石や訪問モデルから開始する最善の方法を使用して、いくつかのグラフを描画する必要があります。

私はすべての訪問が必要な場合は、私が

Visit.group_by_day("started_at", range: 3.month.ago.midnight..Date.today.midnight, format: "%b %-e").order("day asc").count 

を使用していますが、今、私はまた、会社のために、店舗のための訪問をフィルタリングする必要があります。

特定の店舗または特定の会社に所属するユーザーからすべての訪問を取得するにはどうすれば理解できません。

Visit.where("user_id IN (?)", company.users.ids) 

それは動作しますが、私はより良いスコープと私は動作しません書き込みものを書くことprefear:

最も簡単な方法です。

class Visit < ActiveRecord::Base 
    belongs_to :user 

    scope :user_by_store, ->(store_id) { 
    joins(:user).where('user.store_id' => store_id) 
    } 
end 

答えて

1

私はあなたが行うことができるはずだと思う:

scope :by_company, -> (company) { joins(:company).where(company: {id: company}) }