- cjyzpcl
- 等级:
- 性别:
- 文章: 477
- 积分: 402
- 来自: Charlotte
|
需求:场景如下,user可以是多个group的会员,管理者和创建者。group有1个创建者,多个管理者和多个会员。
解决方案:
建立数据库:
sql 代码
- CREATE TABLE `groups` (
- `id` int(11) NOT NULL auto_increment,
- `name` varchar(32) NOT NULL,
- `url` varchar(250) NOT NULL,
- `description` varchar(100) default NULL,
- `logo` int(11) NOT NULL,
- `created_time` datetime NOT NULL,
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-
- CREATE TABLE `users` (
- `id` int(11) NOT NULL auto_increment,
- `logo` int(11) NOT NULL,
- `name` varchar(25) NOT NULL,
- `sex` int(11) NOT NULL,
- `birthday` datetime NOT NULL,
- `location` varchar(100) NOT NULL,
- `hashed_password` varchar(40) NOT NULL,
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-
- CREATE TABLE `members` (
- `id` int(11) NOT NULL,
- `user_id` int(11) NOT NULL,
- `group_id` int(11) NOT NULL,
- `priviledge` varchar(10) default NULL,
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
注意members这个表中的priviledge属性,priviledge属性有3个选择(creator, admin, leaguer),分别代表user在group中的3种身份权限。
model代码:
ruby 代码
- class Member < ActiveRecord::Base
- belongs_to :group
- belongs_to :user
- end
-
- class User < ActiveRecord::Base
- has_many :members
- has_many :groups,
- :through => :members,
- :order => "priviledge desc"
- end
-
- class Group < ActiveRecord::Base
- has_many :members
- has_many :users,
- :through => :members
- has_many :creators,
- :through => :members,
- :source => :user,
- :conditions => ["priviledge = 'creator'"]
- has_many :admins,
- :through => :members,
- :source => :user,
- :conditions => ["priviledge = 'admin'"]
- has_many :leaguers,
- :through => :members,
- :source => :user,
- :conditions => ["priviledge = 'leaguer'"]
- end
这里注意的是
ruby 代码
- has_many :creators,
- :through => :members,
- :source => :user,
- :conditions => ["priviledge = 'creator'"]
不能用has_one来替代,所以替代的方法就是在Group里面加上如下代码:
ruby 代码
- def creator
- creators[0]
- end
这样可以使用Group#creator来得到管理员。
如下代码为测试代码:
ruby 代码
- group = Group.find(2)
- user = User.find(1)
- member = Member.create(:group_id => group, :user_id => user, :priviledge => "admin")
声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
|
返回顶楼 |
|
|
- cjyzpcl
- 等级:
- 性别:
- 文章: 477
- 积分: 402
- 来自: Charlotte
|
发表文章时间更新。
|
返回顶楼 |
|
|