I have a database with table user and table blacklist
In my user model I want to search for if the users ID exists in the blacklists table in the column legacy_logid.
So I define
def blacklist_ip
if Blacklists.legacy_logid == user.id
Blacklists.value
else
nil
end
end
Which seems to me to be a pretty simple way of asking to check the table and see if the userID is in there. But no ..
uninitialized constant User::Blacklists
So how do I access a record in a different table in this model. The legacy_logid is a property of the table - all I want to do is look it up.
If I try with ::Blacklists I get
uninitialized constant Blacklists
If I try
def blacklist_ip
if Blacklist.legacy_logid == user.id
Blacklist.value
else
nil
end
end
I get
Undefined method `legacy_logid' for #<Class:0x00000006407e40>
I have Blacklist defined as
class Blacklist < ActiveRecord::Base
end
Its not a method I want to look up -its a property and yet this seems to be only accessed in an illogical manner.
First of all in rails model names are written in singular while tables are in plural.
So make sure you have a table users
and another blacklists
so that you can access them through User
and Blacklist
models respectively.
You can find whether there is a record in blacklists
with a given user id by doing:
def blacklist_ip
Blacklist.where(legacy_logid: self.id)
end
I suppose relationship between your models is User
has many Blacklist
while Blacklist
belongs to User
.
If you define your User
class like below you'd be able to return all ip blacklisted of a given user:
class User < ActiveRecord::Base
has_many :blacklists
def blacklist_ip
self.blacklists
end
end