首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何覆盖attr_protected?

如何覆盖attr_protected?
EN

Stack Overflow用户
提问于 2010-03-26 22:17:07
回答 2查看 1.2K关注 0票数 2

我实施科学、技术和创新如下:

代码语言:javascript
复制
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私有方法。

代码语言:javascript
复制
class Automobile < ActiveRecord::Base
private
  def attributes_protected_by_default
    super - [self.class.inheritance_column]
  end
end

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

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-04-21 07:12:38

最后我做了这个:

代码语言:javascript
复制
class Automobile < ActiveRecord::Base
private
  def attributes_protected_by_default
    super - [self.class.inheritance_column]
  end
end
票数 1
EN

Stack Overflow用户

发布于 2010-03-27 13:23:14

我将在用户上添加一个助手方法,该方法实例化适当的子类:

代码语言:javascript
复制
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

像这样使用它:

代码语言:javascript
复制
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列。您的解决方案虽然有效,但其缺点是启用攻击。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2527126

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档