开发者

Writing a has_many :through with :conditions association fails due to mass assignment protection

开发者 https://www.devze.com 2023-03-11 02:20 出处:网络
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.

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 cre开发者_如何学JAVAate 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?


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.

0

精彩评论

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