繁体   English   中英

使用委托进行Rails ActiveModel查找

[英]Rails ActiveModel lookup with delegate

我希望这个问题的措词正确,因为我不确定我实际上想完成什么,但是这里...

我在Rails的书中得到了一些建议,即我的数据库逻辑/查找实际上应该在我的模型中处理,而不是在控制器中处理……这是有道理的。 因此,我试图将功能转移到我的模型上,但立即遇到了问题。

在这种情况下,我想找到security_percentage低于99%的主机。

型号/network_host.rb

class NetworkHost < ActiveRecord::Base
  acts_as_paranoid

  belongs_to :location
  has_many :network_host_tests, dependent: :destroy
  has_many :parent_tests, through: :network_host_tests
  has_many :deferred_hosts

  validates_presence_of :location, :mac_address, :ip_address
  validates_uniqueness_of :mac_address

  delegate :security_percentage, to: :last_test, allow_nil: true

  def last_test
    network_host_tests.last
  end

  def test_before_last_test
    network_host_tests.offset(1).last
  end

  def self.hosts_at_risk
    where.not(security_percentage: 99)
  end
end

但是,当在rails console测试我的“新”代码时,我得到了:

$ NetworkHost.hosts_at_risk 
PG::UndefinedColumn: ERROR:  column network_hosts.security_percentage does not exist LINE 1: ...  WHERE "network_hosts"."deleted_at" IS NULL AND ("network_h...
                                                             ^ : SELECT "network_hosts".* FROM "network_hosts"  WHERE
"network_hosts"."deleted_at" IS NULL AND ("network_hosts"."security_percentage" != 99)

我认为这是因为我的delegate :security_percentage, to: ...行。

因此, security_percentage是一个虚拟变量,可通过表network_host_tests找到。

这是我的问题吗? 它可以修复吗?

看起来您只想对正确的表进行联接

def self.hosts_at_risk
  joins(:network_host_tests).where.not(network_host_tests: { security_percentage: 99 })
end

尽管这不仅不再检查上一个测试,它还将检查所有这些。 要将其范围缩小到最后一个测试,您需要做更多的工作,但这有助于了解您的原始控制器正在做的事情

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM