开发者

How to test the membership in a many-to-many relation in Rails3

For example, one user has joined many group; and one group has many user members. Now I get a user object and a group object, I want to know whether this user is a member of this group.

I can see some methods, but still wandering whether ther开发者_开发技巧e is a better way?


So, if i understand your question, what you have is something like:

class User < ActiveRecord::Base
  has_many :groups, :though => :user_members

class Group < ActiveRecord::Base
  has_many :users, :though => :user_members

And you want to know if a user is a member of a specific group.

So, given something like:

u = User.first
g = Group.first

Just do:

u.groups.include? g

Thats all there is to it!

ian.


ipd's way is fine, another more Rails oriented way to do it is :

u.groups.exists?(g)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜