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) 

그것은 작동하지만 더 나은 범위와 I가 작동하지 않습니다 쓰기를 작성하는 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}) }