2

我的 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字段被忽略,因为它是受保护的属性。

我该如何解决这个问题?是否有unprotect受保护属性的声明方式?

编辑: 这是我当前的问题解决方案:我覆盖了attributes_protected_by_default模型类中的私有方法。

class Automobile < ActiveRecord::Base
private
  def attributes_protected_by_default
    super - [self.class.inheritance_column]
  end
end

这将从受保护列表中删除该type字段。

我希望有比这更好的方法。

4

2 回答 2

1

我最终这样做了:

class Automobile < ActiveRecord::Base
private
  def attributes_protected_by_default
    super - [self.class.inheritance_column]
  end
end
于 2010-04-21T07:12:38.200 回答
0

我会在 User 上添加一个辅助方法来实例化适当的子类:

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

上面的代码是“安全的”:攻击者不能将任意文本注入到您的 cars.type 列中。您的解决方案虽然有效,但存在启用攻击的缺点。

于 2010-03-27T13:23:14.443 回答