Let me explain my problem:
I have 2 models:
class User < AR::Base
has_many :contacts
end
class Contact < AR::Base
belongs_to :开发者_如何学Pythonuser
belongs_to :user_contact_id, :class_name => "User", :foreign_key => "user_contact_id" # The "contact" is an ID from the table user.
def self.is_contact?(user_contact_id)
# CHECK IF THE RECORDS EXIST VIA DB OR CACHE OR WHATEVER #
end
end
Having a instance of User as @user, you can check is_contact? like this:
@user.contacts.is_contact?(a_user_id)
This works perfectly, my problem is that I want to access to attributes of @user, inside the is_contact? method in Contact.
Is this possible?
Thank to all you guys.
Short answer:
you don't need is_contact?
, since ActiveRecord already defines a method that does approximately what you want: exist?
@user.contacts.exist? :user_contact_id => a_user_id
Does Contact
have it's own attributes besides id
,user_id
and user_contact_id
?
If not, you might be better off using a has and belongs to many association.
I feel like using something like @user.has_contact? other_user
makes more sense than @user.contacts.is_contact? other_user
You could even roughly keep your current classes by using the :through
option.
class User < AR::Base
has_many :user_contacts
has_many :contacts, :through => :user_contacts,:source => :user_contact_id
def has_contact? user_id
contacts.exists? user_id
end
end
class UserContact < AR::Base
belongs_to :user
belongs_to :user_contact_id,
:class_name => "User",
:foreign_key => "user_contact_id" # The "contact" is an ID from the table user.
end
#
#...
@user.has_contact? other_user.id
Though using has_and_belongs_to_many
would be cleaner, in that you wouldn't even need a model for your join table, just create one in a migration. Then you could
class User < AR::Base
has_and_belongs_to_many :contacts, :class_name => "User",:source => :user_contact_id
def has_contact? user_id
contacts.exists? user_id
end
end
#
#...
@user.has_contact? other_user_id
If you want to access @user attributes, then you should have something like this:
class User < AR::Base
has_many :contacts
end
class Contact < AR::Base
belongs_to :user
belongs_to :user_contact_id, :class_name => "User", :foreign_key => "user_contact_id" # The "contact" is an ID from the table user.
def is_contact?(user_contact_id)
user.firstname = 'John' # just an example
# CHECK IF THE RECORDS EXIST VIA DB OR CACHE OR WHATEVER #
end
end
EDIT:
Yep,right, you also need to change how you call this method. So maybe better solution is to use named_scope
:
# Contact model
named_scope :has_contact, lamda {|user_contact| { :conditions => {:user_contact_id => user_contact } } }
Then you can do:
@user.contacts.has_contact(some_id).count
It will check how many contacts with some_id
has user @user
.
精彩评论