如何重写attr_protected? [英] How to override the attr_protected?

查看:183
本文介绍了如何重写attr_protected?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有性病实现如下:

 类汽车<的ActiveRecord :: Base的
结束

一流的汽车和LT;汽车
结束

一流的卡车和LT;汽车
结束

类用户的LT;的ActiveRecord :: Base的
  的has_many:汽车
  accepts_nested_attributes_for:汽车
结束
 

我建立的汽车的用户的列表。对于每一个汽车,UI设置键入字段,与automobile.While表单提交相关的属性,键入字段被忽略,因为它是被保护的属性。

我如何解决这个问题?是否有声明的形式来取消保护受保护的属性?

编辑: 这是我的问题,目前的解决方案: 我在我的模型类重写 attributes_protected_by_default 私有方法。

 类汽车<的ActiveRecord :: Base的
私人
  高清attributes_protected_by_default
    超 -  [self.class.inheritance_column]
  结束
结束
 

这将删除保护列表中的键入字段。

我希望有一个比这更好的办法。

解决方案

我终于实现了这个

 类汽车<的ActiveRecord :: Base的
私人
  高清attributes_protected_by_default
    超 -  [self.class.inheritance_column]
  结束
结束
 

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.

解决方案

I ended up doing this:

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

这篇关于如何重写attr_protected?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆