0

私の問題を説明しましょう:

私は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 の属性にアクセスしたいということです。お問い合わせの方法。

これは可能ですか?

皆さんに感謝します。

4

2 に答える 2

3

短い答え: は必要ありませんis_contact?。ActiveRecord は、おおよそ必要なことを行うメソッドを既に定義しているためです。exist?

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

、およびContact以外に独自の属性がありますか? そうでない場合は、has および belongs to many 関連付けを使用する方がよい場合があります。iduser_iduser_contact_id

@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
于 2010-02-05T21:22:03.233 に答える
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_iduserを持つ連絡先の数を確認します@user

于 2010-02-05T19:26:02.493 に答える