Rails has_many 具有动态条件 [英] Rails has_many with dynamic conditions
问题描述
我想要的是创建一个模型,它以动态方式使用 has_many 关联与另一个模型连接,没有像这样的外键:
has_many :faixas_aliquotas, :class_name =>'财政::FaixaAliquota',:条件 =>["regra_fiscal = ?", ( lambda { return self.regra_fiscal } ) ]
但我收到错误:
: SELECT * FROM "fis_faixa_aliquota" WHERE ("fis_faixa_aliquota".situacao_fiscal_id = 1AND (regra_fiscal = E'--- !ruby/object:Proc {}'))
这可能吗?
Rails 4+ 方式(感谢 Thomas 在下面回答了这个问题):
has_many :faixas_aliquotas, ->(目的) {where("regra_fiscal = ?", object.regra_fiscal)},:class_name =>'财政:: FaixaAliquota'
Rails 3.1+ 方式:
has_many :faixas_aliquotas, :class_name =>'财政::FaixaAliquota',:条件 =>proc {regra_fiscal = #{self.regra_fiscal}"}
Rails 3 及以下:
has_many :faixas_aliquotas, :class_name =>'财政::FaixaAliquota',:条件 =>['regra_fiscal = #{self.regra_fiscal}']
没有.这不是错误.条件用单引号指定,但仍包含代码 #{self.regra_fiscal}
.在评估条件子句时,将在 self
的对象(无论类是什么)上调用 regra_fiscal 方法.放双引号是行不通的.
我希望这就是你要找的.p>
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?
Rails 4+ way (Thanks to Thomas who answered this below):
has_many :faixas_aliquotas, -> (object) {
where("regra_fiscal = ?", object.regra_fiscal)
},
:class_name => 'Fiscal::FaixaAliquota'
Rails 3.1+ way:
has_many :faixas_aliquotas, :class_name => 'Fiscal::FaixaAliquota',
:conditions => proc { "regra_fiscal = #{self.regra_fiscal}" }
Rails 3 and below:
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.
这篇关于Rails has_many 具有动态条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!