Skip to content

Instantly share code, notes, and snippets.

@dnch
Forked from damncabbage/gist:1350367
Created November 9, 2011 05:02

Revisions

  1. @damncabbage damncabbage revised this gist Nov 9, 2011. No changes.
  2. @damncabbage damncabbage revised this gist Nov 9, 2011. 1 changed file with 17 additions and 4 deletions.
    21 changes: 17 additions & 4 deletions gistfile1.rb
    Original file line number Diff line number Diff line change
    @@ -15,9 +15,22 @@ class Image < ActiveRecord::Base
    Article.protected_attributes # => [:active]
    Article.accessible_attributes # => [] # Where are :title and :body?

    p = Photo.new
    p.attributes # => [:title, :filename, :active]
    Photo.protected_attributes # => [] # Where are :filename and :active?
    Photo.accessible_attributes # => [:title]
    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

  3. @damncabbage damncabbage created this gist Nov 9, 2011.
    23 changes: 23 additions & 0 deletions gistfile1.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,23 @@
    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?

    p = Photo.new
    p.attributes # => [:title, :filename, :active]
    Photo.protected_attributes # => [] # Where are :filename and :active?
    Photo.accessible_attributes # => [:title]