복붙노트

[RUBY-ON-RAILS] 동적 조건 has_many 레일

RUBY-ON-RAILS

동적 조건 has_many 레일

내가 원하는 또 다른와 연결이 같은 외래 키없이, 동적 인 방법에 has_many 연결을 사용하는 모델을 만드는 것입니다 :

has_many :faixas_aliquotas, :class_name => 'Fiscal::FaixaAliquota',
            :conditions => ["regra_fiscal = ?", ( lambda { return self.regra_fiscal } ) ]

그러나 나는 오류를 얻을 :

: SELECT * FROM "fis_faixa_aliquota" WHERE ("fis_faixa_aliquota".situacao_fiscal_id = 1
AND (regra_fiscal = E'--- !ruby/object:Proc {}'))

이게 가능해?

해결법

  1. ==============================

    1.

    has_many :faixas_aliquotas, -> (object) { 
               where("regra_fiscal = ?", object.regra_fiscal)
             },
             :class_name => 'Fiscal::FaixaAliquota'
    
    has_many :faixas_aliquotas, :class_name => 'Fiscal::FaixaAliquota',
             :conditions => proc { "regra_fiscal = #{self.regra_fiscal}" }
    
    has_many :faixas_aliquotas, :class_name => 'Fiscal::FaixaAliquota',
             :conditions => ['regra_fiscal = #{self.regra_fiscal}']
    

    제이 실수하지 않습니다. 조건은 작은 따옴표로 지정된 여전히 코드 # {self.regra_fiscal}을 포함하고 있습니다. 조건 절을 evaulated 때, regra_fiscal 방법은 자기의 객체 (클래스가 무엇이든)에 호출됩니다. 퍼팅 따옴표가 작동하지 않습니다.

    나는 이것이 당신이 찾고있는 무엇인가를 바란다.

  2. ==============================

    2.4+ 방법을 레일 :

    4+ 방법을 레일 :

    has_many :faixas_aliquotas, 
             -> (object){ where("regra_fiscal = ?", object.regra_fiscal)},  
             :class_name => 'Fiscal::FaixaAliquota'
    
  3. ==============================

    3.솔루션의 또 다른 종류가있다. 그러나,이 습관은 기본 범위합니다.

    솔루션의 또 다른 종류가있다. 그러나,이 습관은 기본 범위합니다.

    has_many :faixas_aliquotas, :class_name => 'Fiscal::FaixaAliquota' do 
      def filter(situacao_fiscal)
        find(:all, :conditions => {:regra_fiscal => situacao_fiscal.regra_fiscal})
      end
    end
    

    당신이 할 수있을 것입니다 이런 식으로

    situacao_fiscal.faixas_aliquotas.filter(situacao_fiscal)
    

    이 우아하고 문제를 해결할 뭔가가 있는지 확실하지 않다. 이 일을 더 나은 방법이있을 수 있습니다.

  4. ==============================

    4.레일은 다른 방법을 4+ :

    레일은 다른 방법을 4+ :

    has_many :faixas_aliquotas, -> (object){ where(regra_fiscal: object.regra_fiscal) }, :class_name => 'Fiscal::FaixaAliquota'
    
  5. ==============================

    5.레일에서 사용 PROC 3.1 필요성, Proc.new { "필드 = # {self.send (: other_field)}"}

    레일에서 사용 PROC 3.1 필요성, Proc.new { "필드 = # {self.send (: other_field)}"}

  6. ==============================

    6.레일 3.1 당신은 당신의 조건 Proc.new를 사용할 수 있습니다. @Amala에 의해 명시된 바와 같이, 대신에이 같은 해시를 생성 :

    레일 3.1 당신은 당신의 조건 Proc.new를 사용할 수 있습니다. @Amala에 의해 명시된 바와 같이, 대신에이 같은 해시를 생성 :

    has_many :faixas_aliquotas, :class_name => 'Fiscal::FaixaAliquota',
       :conditions => {:regra_fiscal => Proc.new { {:regra_fiscal => self.regra_fiscal} }
    

    이 방법의 장점은 object.faixas_aliquotas.build 할 경우, 새로 생성 된 객체가 자동으로 부모와 같은 regra_fiscal 특성이있는 것입니다.

  7. from https://stackoverflow.com/questions/2462203/rails-has-many-with-dynamic-conditions by cc-by-sa and MIT license