-
-
Save dnch/1350453 to your computer and use it in GitHub Desktop.
Calculating Mass-Assignable ActiveRecord Attributes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Article < ActiveRecord::Base | |
# Has attributes: :title, :body, :active | |
attr_protected :active | |
end | |
class Image < ActiveRecord::Base | |
# Has attributes: :title, :filename, :active | |
attr_accessible :title | |
end | |
a = Article.new | |
a.attributes # => [:title, :body, :active] | |
Article.protected_attributes # => [:active] | |
Article.accessible_attributes # => [] # Where are :title and :body? | |
i = Image.new | |
i.attributes # => [:title, :filename, :active] | |
Image.protected_attributes # => [] # Where are :filename and :active? | |
Image.accessible_attributes # => [:title] | |
# Possible to calculate sort of like the following, but something in ActiveRecord | |
# should already be doing this... Right? :| | |
# NOTE: Foreign key columns and timestamp columns are included; they must be marked | |
# as protected in a way that doesn't show up in protected_attributes. | |
def assignable_attributes(record) | |
assignable = [] | |
assignable = record.attributes.keys - record.class.protected_attributes.to_a unless record.class.protected_attributes.empty? | |
assignable = record.class.accessible_attributes.to_a unless record.class.accessible_attributes.empty? | |
assignable | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment