Writing a has_many :through with :conditions association fails due to mass assignment protection
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.
精彩评论