views:

200

answers:

2

Hello!

What I want is to create a Model that connects with another using a has_many association in a dynamic way, without the foreign key like this:

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

But I get the error:

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

Is this possible?

+1  A: 
has_many :faixas_aliquotas, :class_name => 'Fiscal::FaixaAliquota',
        :conditions => ['regra_fiscal = #{self.regra_fiscal}']

No. This is not a mistake. The conditions are specified in single quotes and still contains the code #{self.regra_fiscal}. When the conditions clause is evaulated, the regra_fiscal method will be called on the object of self (whatever the class is). Putting double quotes will not work.

I hope this is what you are looking for.

Chirantan
+1 Just tried, and got: >> SituacaoFiscal.last.faixas_aliquotasNameError: uninitialized constant SituacaoFiscal from /home/fabiano/workspace/sgi/vendor/rails/activesupport/lib/active_support/dependencies.rb:443:in `load_missing_constant' from /home/fabiano/workspace/sgi/vendor/rails/activesupport/lib/active_support/dependencies.rb:80:in `const_missing' from /home/fabiano/workspace/sgi/vendor/rails/activesupport/lib/active_support/dependencies.rb:92:in `const_missing' likely because my class name is: 'Fiscal::SituacaoFiscal'
Fabiano PS
I'm not sure how to handle the scope, you might want to try some stuff around this solution.
Chirantan
Worked perfectly now! Likely I was doing something wrong in my class before; tnxs!
Fabiano PS
+1  A: 

There is another kind of solution. However, this wont be the default scope.

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

This way you would be able to do

situacao_fiscal.faixas_aliquotas.filter(situacao_fiscal)

I am not sure if this is elegant and something that would solve your problem. There may be better ways of doing this.

Chirantan
+1 Also a very good one in some cases
Fabiano PS