如何获得的activerecord模型,可以是属性列表质量分配 [英] How to get the list of attributes of a activerecord model that can be mass-assigned

查看:164
本文介绍了如何获得的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 a model like :

class Post < ActiveRecord::Base
  attr_protected :account

  belongs_to :author

  validates_presence_of :title, :author
end

我想有结果包含列表:作者:标题

I would like to have as a result a list containing :author, :title.

如果这样的方法存在任何想法?或者一些对我怎么可以让一个没有这种指引?

Any idea if such a method exists? Or some guidelines on how I can make one that does this?

推荐答案

Post.accessible_attributes将覆盖它,如果你明确定义attr_accessible

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天全站免登陆