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?
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.