如何覆盖 attr_protected?
我的 STI 实现如下:
class Automobile < ActiveRecord::Base
end
class Car < Automobile
end
class Truck < Automobile
end
class User < ActiveRecord::Base
has_many :automobiles
accepts_nested_attributes_for :automobiles
end
我正在为用户创建汽车列表。对于每辆汽车,UI 都会设置 type
字段以及与汽车关联的属性。提交表单时,type
字段将被忽略,因为它是受保护的属性。
我该如何解决这个问题?是否有一种声明性方式来取消保护
受保护的属性?
编辑: 这是我目前的问题解决方案: 我在模型类中重写了 attributes_protected_by_default
私有方法。
class Automobile < ActiveRecord::Base
private
def attributes_protected_by_default
super - [self.class.inheritance_column]
end
end
这将从受保护列表中删除 type
字段。
我希望有比这更好的方法。
I have STI implementation as follows:
class Automobile < ActiveRecord::Base
end
class Car < Automobile
end
class Truck < Automobile
end
class User < ActiveRecord::Base
has_many :automobiles
accepts_nested_attributes_for :automobiles
end
I am creating a list of automobiles for a user. For each automobile, the UI sets the type
field and the properties associated with the automobile.While form submission, the type
field is ignored as it is a protected attribute.
How do I work around this issue? Is there a declarative way to unprotect
a protected attribute?
Edit:
This is my current solution for the problem:
I override the attributes_protected_by_default
private method in my model class.
class Automobile < ActiveRecord::Base
private
def attributes_protected_by_default
super - [self.class.inheritance_column]
end
end
This removes the type
field from the protected list.
I am hoping that there is a better way than this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我最终这样做了:
I ended up doing this:
我会在 User 上添加一个帮助器方法来实例化适当的子类:
像这样使用它:
上面的代码是“安全的”:攻击者无法将任意文本注入到 cars.type 列中。您的解决方案虽然有效,但存在引发攻击的缺点。
I would add a helper method on User that instantiates the appropriate subclass:
Use it like this:
The code above is "safe": an attacker can't inject arbitrary text into your automobiles.type column. Your solution, while it works, has the disadvantage of enabling attacks.