在Rails中,如何在首次创建对象时仍然允许设置属性的同时保护属性免受批量分配? [英] In Rails, how can I protect an attribute from mass assignment while still allowing the attribute to be set when the object is first created?
问题描述
我现在只和Rails一起工作了几个月,所以我可能会遗漏一些明显的东西,但是如果attr_accessible
或attr_protected
保护了一个属性免受批量分配,那么如何设置该属性?您首先创建记录? (并以仍然安全的方式进行操作.)
I've only been working with Rails for a few months now so I may be missing something obvious, but if an attribute is protected from mass assignment by attr_accessible
, or attr_protected
, how do you set that attribute when you first create a record? (And do it in a way that is still secure.)
例如:
说我正在开发一个应用程序,该应用程序可以跟踪公司员工接受过培训的不同程序和流程.
Say I'm working on an application that keeps track of different procedures and processes that employees in a company have been trained on.
作为此应用程序的一部分,我有三个模型:User
,Course
和TrainingClass
. User
代表员工,Course
代表员工可以接受的不同培训,TrainingClass
代表员工在课程中接受培训的特定班级.
As part of this application, I have three models: User
, Course
, and TrainingClass
. User
represents employees, Course
represents different things employees can be trained on, and TrainingClass
represents a specific class in which employees will be trained on a course.
TrainingClass
与Course
模型(因为一个类基本上只是一门课程的特定实例)和User
模型(因为该类只有一个讲师,两者都具有belongs_to
关系)是创建TrainingClass
的用户).同样,Course
和User
模型与TrainingClass
模型都具有has_many
关系.
The TrainingClass
has a belongs_to
relationship with both the Course
model (because a class is basically just a specific instance of a course) and the User
model (because the class has a single instructor, who is the user who creates the TrainingClass
). Similarly, the Course
and User
models both have a has_many
relationship with the TrainingClass
model.
基于这些信息,我将如何为TrainingClass
创建新记录?
Based on that information, how would I go about creating a new record for TrainingClass
?
我可以说:
course.training_classes.build(user_id: user.id)
或
user.training_classes.build(course_id: course.id)
但这不是对user_id
或course_id
属性的批量分配吗?
But wouldn't that be mass assignment on the user_id
or course_id
attributes?
在保持应用程序安全的同时做到这一点的最佳方法是什么?
What would be the best way to do this while still keeping the application secure?
推荐答案
阅读有关批量分配安全性,尤其是角色.
您可以拥有
class TraningClass < ActiveRecord::Base
attr_accessible .....
attr_accessible ....., :user_id, as: :create
end
其中......
是您要访问的其他属性的列表,以进行批量分配.然后,当您呼叫build
时,您将通过该角色
Where ......
is your list of other attributes you want accessible for mass assignment. Then when you call build
, you'll pass that role
course.training_classes.build({user_id: user.id}, as: :create)
对其他型号重复同样的操作.除非您在调用build
,create!
等时指定:create
角色,否则将使用默认角色(第一个).
Repeat similarly for your other models. The default role will be used (the first one) unless you specify the :create
role when calling build
, create!
, etc...
这篇关于在Rails中,如何在首次创建对象时仍然允许设置属性的同时保护属性免受批量分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!