0

コミュニティの一意のコードを持つユーザーの数を表示しようとしています。

@community.uniquecodes.users.count.to_s

これがこのエラーを返すのはなぜですか?

undefined method `users' 

ユニークコードは残っているのにユーザーが削除される可能性があることを考慮してください!

私の協会はこんな感じです

User has_many :communities
     has_many :uniquecodes

Community belongs_to :user
          has_many :uniquecodes

Uniquecode belongs_to :user
           belongs_to :community

コミュニティの一意のコードを持つユーザーの数を取得するにはどうすればよいですか?

4

3 に答える 3

1

あなたの関係は明確ではありません.おそらく has_many :through 関連付けのようなものが必要ですが、「belongs_to :user」は私を少し混乱させます.uniquecodeはどういう意味ですか?

試してみてください

User has_one :community
     has_many :uniquecodes
     has_many :communities, :though => :uniquecodes

Community belongs_to :user
          has_many :uniquecodes
          has_many :users, :through => :uniquecodes

Uniquecode belongs_to :user
           belongs_to :community

また、uniquecode は単なる結合モデルだと思うので、ユーザーが削除された場合は存在しないはずです (has_many, :through アソシエーションが自動的に処理します)。

そうすれば、「community.users」を実行できます

于 2013-01-23T19:15:14.493 に答える
1

試す:

Community has_many :uniquecodes
Uniquecode has_many :users

これでうまくいくはずです:

@community.uniquecodes.users.count.to_s
于 2013-01-23T18:53:19.470 に答える
1

メソッドチェーンに #try を使用する

Rails のObject#tryメソッドは、nil の可能性があるオブジェクトでメソッドを呼び出す場合に便利です。次の点を考慮してください。

1.9.3p362 :001 > @foo = []
 => [] 
1.9.3p362 :002 > @foo.count
 => 0 
1.9.3p362 :003 > @foo = nil
 => nil 
1.9.3p362 :004 > @foo.count
NoMethodError: undefined method `count' for nil:NilClass
1.9.3p362 :005 > @foo.try(:count)
 => nil 

のようなメソッド チェーンの問題の 1 つ@community.uniquecodes.users.count.to_sは、チェーンに沿ったメソッドが nil を返す場合、NilClass のインスタンスで次のメソッドを呼び出すことになることです。:try メソッドは、そのような場合に NoMethodError 例外が発生するのを防ぎ@foo.some_method rescue nilます。ただし、rescue 句とは異なり、Object#try は連鎖可能です。

于 2013-01-23T19:01:09.270 に答える