簡體   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