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

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

问题描述

我想要的是创建一个模型,该模型使用has_many关联以动态方式与另一个模型连接,而无需像这样的外键:

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 } ) ]

但是我得到了错误:

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

这可能吗?

推荐答案

采用4种以上的方法(感谢托马斯在下面回答了此问题):

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

Rails 3.1+方式:

has_many :faixas_aliquotas, :class_name => 'Fiscal::FaixaAliquota',
         :conditions => proc { "regra_fiscal = #{self.regra_fiscal}" }

路轨3及以下:

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

不.这不是一个错误.条件用单引号引起来,并且仍然包含代码#{self.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.

我希望这是您想要的.

这篇关于Rails has_many具有动态条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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