Rails 模型使用连接写入 def [英] Rails model write def with a join

查看:24
本文介绍了Rails 模型使用连接写入 def的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为工单"模型中的可计费"建立定义.

I'm trying to establish a def for "billable" in the model for "Workorders".

关系:

  Workorders - belongs_to :billmethod
  Billmethod - has_many :workorders

我试过这些:

  def self.billable
    joins(:billmethods).where(billmethods: {"method_name != ?", 'Not Billable'})
  end

def self.billable
  where("billmethod.method_name != ?", 'Not Billable')
end

推荐答案

您需要使用与您在 has_many/belongs_to 中定义的名称相同的名称(但始终在 where() 方法:

You need to use the same name as you defined in the has_many / belongs_to (but always use the pluralized name in the where() method:

如果:

class Workorder < ActiveRecord::Base    
  belongs_to :billmethod
              #        ^^

那么:

def self.billable
  joins(:billmethod).where('billmethods.method_name != ?', 'Not Billable')
        #         ^^                 
end

<小时>

如果:

class Workorder < ActiveRecord::Base    
  has_many :billmethods
              #       ^

那么:

def self.billable
  joins(:billmethods).where('billmethods.method_name != ?', 'Not Billable')
        #          ^                 
end

这篇关于Rails 模型使用连接写入 def的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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