ActiveRecord:如何获取可以批量分配的模型的所有属性? [英] ActiveRecord: How to get all attributes of a model that can be mass-assigned?

查看:48
本文介绍了ActiveRecord:如何获取可以批量分配的模型的所有属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个可以批量分配的所有属性名称的列表。对于自定义表单生成器,我将需要它,默认情况下不会添加无法批量分配的输入字段。

I would like to have a list of all attribute names that can be mass assigned. I need this for a custom form builder that will not add input fields by default that cannot be mass assigned.

例如,如果我有以下模型:

For example if I have the following model:

class Post < ActiveRecord::Base
  attr_protected :account

  belongs_to :author

  validates_presence_of :title, :author
end

因此,我希望拥有 [:author,:title]

推荐答案

如果您明确定义了attr_accessible,则Post.accessible_attributes将覆盖该问题

Post.accessible_attributes would cover it if you explicitly defined attr_accessible

除非这样做,否则这样做很笨拙,但可以:

Barring, that, doing something like this is clunky but works:

Post.new.attributes.keys - Post.protected_attributes.to_a

这篇关于ActiveRecord:如何获取可以批量分配的模型的所有属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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