【问题标题】:Ruby On Rails - How to get the Object Method CallerRuby On Rails - 如何获取对象方法调用者
【发布时间】:2010-02-05 19:09:58
【问题描述】:

让我解释一下我的问题:

我有 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,你可以检查is_contact吗?像这样:

@user.contacts.is_contact?(a_user_id)

这很好用,我的问题是我想在 is_contact 中访问@user 的属性?联系方式。

这可能吗?

谢谢大家。

【问题讨论】:

  • 问题是我正在开发一个巨大的约会网站,所以我需要将一些列表带到 Memcache 或东京内阁。为此,我想控制 self.is_contact? 的所有内容。在开发中,我可以使用 AR 进行检查,而对于生产,我可以使用其他东西。我的问题不是如何检查联系人是否存在,这很容易。我的问题是在 self.is_contact 中访问@user?在将方法调用为@user.contacts.is_contact?(some_user) 谢谢

标签: ruby-on-rails ruby activerecord rails-models


【解决方案1】:

简短回答: 你不需要is_contact?,因为 ActiveRecord 已经定义了一个方法,可以大致完成你想要的:exist?

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

Contact 除了iduser_iduser_contact_id 之外,是否还有自己的属性? 如果没有,最好使用 has 和 belongs to many 关联。

我觉得使用 @user.has_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 会更简洁,因为您甚至不需要连接表的模型,只需在迁移中创建一个即可。那你就可以

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

【讨论】:

    【解决方案2】:

    如果你想访问@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

    【讨论】:

    • 他还需要更改他的方法调用 - user.contacts.select{|c| c.is_contact?(id)},或类似的东西。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多