具有动态条件的 Rails has_many [英] Rails has_many with dynamic conditions

查看:23
本文介绍了具有动态条件的 Rails has_many的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要的是创建一个使用 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',:条件=>过程 {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 方法(无论类是什么).加上双引号是行不通的.

我希望这就是你要找的.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆