Ruby-on-rails ActiveRecord:如何获取可以批量分配的模型的所有属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1526066/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:50:08  来源:igfitidea点击:

ActiveRecord: How to get all attributes of a model that can be mass-assigned?

ruby-on-railsactiverecord

提问by Vincent

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

I would like to have as a result [:author, :title].

我想有这样的结果[:author, :title]

回答by semanticart

Post.accessible_attributes would cover it if you explicitly defined attr_accessible

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

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

除非,做这样的事情很笨拙但有效:

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

回答by Victor S

Some of the previously mentioned answers may not apply for Rails 4.

前面提到的一些答案可能不适用于 Rails 4。

You can use MyModel.attribute_namesto get the array of table attributes, although, that might not give you mass assignable attributes, as this aspect of Rails changes with version 4 http://weblog.rubyonrails.org/2012/3/21/strong-parameters/

您可以使用MyModel.attribute_names来获取表属性数组,尽管这可能不会为您提供大量可分配的属性,因为 Rails 的这一方面随着版本 4 http://weblog.rubyonrails.org/2012/3/21/strong-parameters发生变化/

回答by Antoine

Just use

只需使用

Post.accessible_attributes

That will return all the attributes accessibleof the class

这将返回该类的所有可访问属性

回答by Scudelletti

For Models you can use MyModel.attribute_namesor MyModel.column_names.

对于模型,您可以使用MyModel.attribute_namesMyModel.column_names

For instances you can use MyModel.new.attribute_names.

例如,您可以使用MyModel.new.attribute_names.

回答by Rajesh Paul

Post.accessible_attributes.to_a.map(&:to_sym)

Post.accessible_attributes.to_a.map(&:to_sym)