Godzilla74 Godzilla74 - 5 months ago 10
Ruby Question

Rails ActiveModel lookup with delegate

I hope the question is worded correctly since I'm unsure of what I am actually trying to accomplish, but here goes...

I got some advice in a Rails book that my DB logic/lookups should actually be handled in my Models instead of Controllers... that makes sense. So, I'm trying to move over the functionality to my Models, but running into an issue right off the bat.

In this case, I'd like to find hosts with a

security_percentage
below 99%.


models/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


However, when testing my 'new' code out in the
rails console
, I get this:

$ 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)


I assume this is because of my
delegate :security_percentage, to: ...
line.

So,
security_percentage
is a virtual variable, found through the table
network_host_tests
.

Is this my issue? Is it fixable?

TMP TMP
Answer

It looks like you just want to do a joins to the correct table

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

Although this isn't just checking the last test anymore, it would be checking all of them. To narrow it down to the last test you'd have to do some more work, but it'd help to know what your original controller was doing to get it

Comments