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?
In Rails 3.1 need to use proc, Proc.new { "field = #{self.send(:other_field)}" }
There is another kind of solution. However, this wont be the default scope.
This way you would be able to do
I am not sure if this is elegant and something that would solve your problem. There may be better ways of doing this.
Rails 4+ another way:
Rails 4+ way:
In Rails 3.1 you can use Proc.new for your conditions. as stated by @Amala, but instead generate a hash like this:
The benefit of this approach is that if you do
object.faixas_aliquotas.build
, the newly created object will automatically have the sameregra_fiscal
attribute as the parent.Rails 4+ way (Thanks to Thomas who answered this below):
Rails 3.1+ way:
Rails 3 and below:
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 ofself
(whatever the class is). Putting double quotes will not work.I hope this is what you are looking for.