3 ms·
I'm a stickler for attr_accessible, but I've never heard of avoiding _id attributes. If a have an Employee model, what is wrong with `attr_accessible :departmen
by pjungwir 13y ago
I'm a stickler for attr_accessible, but I've never heard of avoiding _id attributes. If a have an Employee model, what is wrong with `attr_accessible :department_id` (assuming I want to permit changing the department)?
- phillmv 13y agoIt depends on your app. Suppose you have some kind of permissions model based around the department that a certain employee belongs to. Say, HR people can look at people's salaries. If you allow mass assignment to department_id, someone can edit the form in the user page and assign themselves to ANY department and boom!, they're in. You can fix this by having some sort of validation, but I find I prefer to have it in the controller. Before: @model.update_attributes(params[:model]) # trololol After dept = params[:model].delete[:department_id] @model.update_attributes(params[:model]) if current_user.can(:foo) @model.department = Department.find(dept) end If I've got this wrong, please let me know. I'm pretty sure the above is basically the whole point of using attr_accessible (aside from the fact that they now force you to use it; was not the case <3.2 iirc)
- pjungwir 13y agoOkay, so it just comes down to whether or not the user should be allowed to edit the FK relationship or not. You may be interested to know that you can have multiple attr_accessible declarations for different classes of user, and then when you call update_attributes you say which declaration should apply. But perhaps with strong parameters it's not worth going down that road.