簡體   English   中英

Ruby On Rails-如何獲取對象方法調用者

[英]Ruby On Rails - How to get the Object Method Caller

讓我解釋一下我的問題:

我有2個型號:

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 self.is_contact?(user_contact_id)
  # CHECK IF THE RECORDS EXIST VIA DB OR CACHE OR WHATEVER #
 end
end

將User的實例設為@user,可以檢查is_contact? 像這樣:

@user.contacts.is_contact?(a_user_id)

這完美地工作了,我的問題是我想訪問is_contact內部的@user屬性? 聯系中的方法。

這可能嗎?

謝謝大家。

簡短的答案:您不需要is_contact? ,因為ActiveRecord已經定義了一種方法,該方法可以滿足您的需求: exist?

  @user.contacts.exist? :user_contact_id => a_user_id

iduser_iduser_contact_id之外, Contact是否具有其自己的屬性? 如果不是,您最好使用has並屬於許多關聯。

我想使用類似@user.has_contact? other_user東西@user.has_contact? other_user @user.has_contact? other_user@user.contacts.is_contact? other_user更有意義@user.contacts.is_contact? other_user @user.contacts.is_contact? other_user

您甚至可以使用:through選項大致保留當前的類。

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

盡管使用has_and_belongs_to_many會更干凈,但是您甚至不需要為has_and_belongs_to_many表創建模型,只需在遷移中創建一個模型即可。 那你可以

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

如果要訪問@user屬性,則應具有以下內容:

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

編輯:

是的,對,您還需要更改此方法的調用方式。 因此,也許更好的解決方案是使用named_scope

# Contact model
named_scope :has_contact, lamda {|user_contact| { :conditions => {:user_contact_id => user_contact } } }

然后,您可以執行以下操作:

@user.contacts.has_contact(some_id).count

它會檢查了多少個聯系人與some_id有用戶@user

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM