由于批量赋值保护,编写 has_many :through 与 :conditions 关联失败
我有 3 个类:组和用户,通过名为“成员资格”的连接表连接。成员资格有一个属性“角色”,它告诉我们用户在组中扮演的角色。
一个组
has_many :leaderships, :class_name => 'Membership', :conditions => {:role => "leader"}
has_many :leaders, :through => :leaderships, :source => :user
这让我可以说
g = group.new
g.leaders.build(:name => 'Tom')
,通过Rails的魔力,我得到了这个SQL(同时还向用户插入一条记录),
INSERT INTO `memberships` (`group_id`, `role`, `user_id`) VALUES (262, 'leader', 1291)
即,它实际上知道创建一个角色=“领导者”的成员资格。欢呼。
然而,当我将“角色”设置为 attr_protected 时,这就中断了。我真的无法禁用此功能,因为我有点担心人们能够编辑表单以将其角色升级为领导者。
有什么建议吗?
I have 3 classes: Group and User, connected by a join table called Membership. Membership has a attribute "role" which tells us about the role that user is playing in the group.
A group
has_many :leaderships, :class_name => 'Membership', :conditions => {:role => "leader"}
has_many :leaders, :through => :leaderships, :source => :user
This allows me to say
g = group.new
g.leaders.build(:name => 'Tom')
And by the magic of Rails, I get this SQL (along with also inserting a record into users)
INSERT INTO `memberships` (`group_id`, `role`, `user_id`) VALUES (262, 'leader', 1291)
Ie, it actually knows to create a membership with role = "leader". Hurrah.
However, this breaks when I make "role" an attr_protected. And I really can't disable this, because I'm a little worried that people will be able to edit an form to upgrade their role to leader.
Any tips?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您是否考虑过使用 before_save 过滤器来保护“角色”字段不被不应访问的用户访问?这样你就可以放弃
attr_protected
。在我正在开发的应用程序中,我们使用设计和设置自定义权限,并在保存之前立即检查所选字段的权限。
Have you considered a before_save filter to protect the "role" field from users that shouldn't be accessing it? that way you can leave off
attr_protected
.In the app I am working on we use devise and a custom permissions set up and simply check permissions on select fields immediately before save.