2014-08-29 5 views
0

나는 판매 된 회사를 기준으로 제품 판매 단위의 평균을 계산해야하는 경우가 있습니다. 거기에서 나는 판매 된 단위에 대한 백분율 차이를 계산할 것입니다. 제품이 포함 된 모델이 하나 있습니다.평균적으로 속성을 기준으로 평균 계산

  • 제품 _
  • unit_sold 많은 회사가 있습니다

  • 기업 : 각 제품의 특성을가집니다.

    이 코드는 모든 레코드의 평균을 계산하는 데 사용되지만 조건 '회사'를 기준으로 평균적으로 평균을 계산하고 싶습니다.

    def average_UnitSold 
        self.class.average(:unit_sold) 
        end 
    
    def averagechange_UnitSold 
         (self.unit_sold - average_UnitSold)/average_UnitSold * 100 
        end 
    

    나는이 함께했다, 그러나 그것은 작동하지 않습니다 :

    def average_UnitSold 
         self.class.sum(:unit_sold), :conditions => "company = self.company"))/:unit_sold 
        end 
    

    어떤 아이디어?

    또 다른 주목할 점은 이러한 모든 평균을 어딘가에 저장하고 일상적으로보다 효율적으로 업데이트하는 것이 가능한 실용적인 접근 방법입니까? 대답을 기반으로

    , 지금이 코드를 구현하고, 그것을 작동하는 것 같다 :

    def self.average_unit_sold(company) 
        where(company: company).average(:unit_sold) 
    end 
    
    def average_unit_sold 
          self.class.average_unit_sold(self.company) 
         end 
    
    def averagechange_UnitSold 
         (self.unit_sold - average_unit_sold)/average_unit_sold * 100 
        end 
    
  • +0

    당신이 사이에 연관성이 있습니까 당신의 모델? 그것은 놀라 울 정도로 간단한 일이 될 것입니다. –

    +0

    안녕하세요,이 – bnussey

    +0

    '회사'모델에 대한 하나의 모델 만 있습니다. 그거 이상 하네. 데이터 구조가 제안합니다. @infused는 그의 답변에서 내가 의미하는 것을 보여 주었다. –

    답변

    1

    그것은 결과가 실제로하지 않기 때문에 당신이 인스턴스 메서드에서이 작업을하고있는 것은 매우 이상하다 특정 인스턴스와 관련이있다. 당신이 정말는 인스턴스 메서드를 원한다면

    class Product < ActiveRecord::Base 
        # `self.average_unit_sold` is a class method that takes `company` as an 
        # argument and executes an SQL query like this (where 'some_company' is the 
        # company given in the argument): 
        # 
        #  SELECT AVG(products.unit_sold) FROM products 
        #  WHERE products.company = 'some_company' 
        # 
        def self.average_unit_sold(company) 
        where(company: company).average(:unit_sold) 
        end 
    end 
    
    # ...then... 
    Product.average_unit_sold(some_company) 
    

    , 당신이 하나를 추가 할 수 있습니다 (그러나 클래스 메서드의 논리를 유지) : 대신, 클래스 메소드를 정의

    # `average_unit_sold` is an instance method that takes the value of the 
    # instance's own `company` attribute and calls `Product.average_unit_sold`: 
    def average_unit_sold 
        self.class.average_unit_sold(self.company) 
    end 
    

    (이 scope 일 수도 있지만 심미적 인 이유 때문에 모델 인스턴스 또는 인스턴스 컬렉션 인 경우에만 스코프를 사용하는 것이 좋습니다.

    +0

    답변 주셔서 감사합니다, 위의 코드에 추가하고 작동하는 것 .. 왜 설명하는 데 도움이 될 수 있을까요?나는 루비를 처음 사용합니다. – bnussey

    +0

    @bnussey 꽤 기본 적이기 때문에 레일즈 문서보다 더 잘 설명 할 수 있다고 생각하지 않습니다. Rails 모델의 작동 방식에 대한 개요는 [Active Record Basics] (http://guides.rubyonrails.org/active_record_basics.html)를 읽고 [Active Record Query Interface] (http://guides.rubyonrails.org/active_record_querying)를 참조하십시오. .html)를 사용하여 Rails에서 데이터베이스 쿼리가 작동하는 방식을 이해할 수 있습니다. 결국에는 [Rails Guides] (http://guides.rubyonrails.org/)를 모두 읽으려는 경향이 있습니다. –

    +0

    그 점과 그 해답에 대한 자세한 설명을 추가해 주셔서 감사합니다. – bnussey

    1

    연결이 올바르게 설정되었다고 가정하면 나는 성취하기가 꽤 쉽습니다. 한 회사에 판매

    Product.average(:unit_sold) 
    

    평균 단위 : 모든 기업에 판매

    class Company < ActiveRecord::Base 
        has_many :products 
    end 
    
    class Product < ActiveRecord::Base 
        belongs_to :company 
    end 
    

    평균 단위 : 그래서 회사는 많은 제품이 있다고 가정

    company = Company.find(1) 
    company.products.average(:unit_sold) 
    
    +0

    안녕하십니까 @ 데이터가 응용 프로그램에서 작성되지는 않았지만 외부 소스에서 가져온 것이므로 이러한 연관은 설정되지 않았습니다. 이 일을 할 때 어떤 이점이 있습니까? – bnussey