我实施科学、技术和创新如下:
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字段和与automobile.While表单提交相关的属性,type字段被忽略,因为它是一个受保护的属性。
我该如何解决这个问题?是否有一种声明式的方法来unprotect一个受保护的属性?
编辑:--这是我当前的问题解决方案:我在模型类中重写了attributes_protected_by_default私有方法。
class Automobile < ActiveRecord::Base
private
def attributes_protected_by_default
super - [self.class.inheritance_column]
end
end这将从受保护列表中移除type字段。
我希望有比这更好的方法。
发布于 2010-04-21 07:12:38
最后我做了这个:
class Automobile < ActiveRecord::Base
private
def attributes_protected_by_default
super - [self.class.inheritance_column]
end
end发布于 2010-03-27 13:23:14
我将在用户上添加一个助手方法,该方法实例化适当的子类:
class User < ActiveRecord::Base
def self.automobile_from_type(type)
self.automobiles << case type
when "Car"
Car.new
when "Truck"
Truck.new
else
raise ArgumentError, "Unknown automobile type: #{type.inspect}"
end
end
end像这样使用它:
class AutomobilesController < ApplicationController
def create
@automobile = current_user.automobile_from_type(params[:automobile][:type])
if @automobile.update_attributes(params[:automobile]) then
redirect_to @automobile
else
render :action => :new
end
end
end上面的代码是“安全的”:攻击者不能将任意文本注入您的automobiles.type列。您的解决方案虽然有效,但其缺点是启用攻击。
https://stackoverflow.com/questions/2527126
复制相似问题