attr_accessible in rails Active Record

后端 未结 5 1435
轻奢々
轻奢々 2020-12-10 05:09

When I use the attr_accessible to specify which fields from my Model I will expose, is it true for script/console as well? I mean something that I didn\'t speci

相关标签:
5条回答
  • 2020-12-10 05:48

    This is only true for mass assignment. For instance, if you were to set attr_protected :protected in your model:

    >> Person.new(:protected => "test")
    => #<Person protected: nil>
    

    Conversely, you could set all attributes you want as accessible using attr_accessible.

    However, the following will still work:

    >> person = Person.new
    => #<Person protected: nil>
    >> person.protected = "test"
    => #<Person protected: "test">
    

    This is the same behaviour as in controllers, views, etc. attr_protected only protects against mass assignment of variables, primarily from forms, etc.

    0 讨论(0)
  • 2020-12-10 05:57

    The console behaves exactly as your Rails application. If you protected some attributes for a specific model, you won't be able to mass assign these attributes either from console or from the Rails app itself.

    0 讨论(0)
  • 2020-12-10 06:02

    I found why:

    Specifies a white list of model attributes that can be set via mass-assignment, such as new(attributes), update_attributes(attributes), or attributes=(attributes). This is the opposite of the attr_protected macro:

     Mass-assignment will only set attributes in this list, to assign to the rest of 
    attributes you can use direct writer methods. This is meant to protect sensitive  
    attributes from being overwritten by malicious users tampering with URLs or forms. 
    If you‘d rather start from an all-open default and restrict attributes as needed,
    have a look at `attr_protected`.
    

    So it means that it just avoid mass-assignment but i can still set a value.

    0 讨论(0)
  • 2020-12-10 06:05

    When you specify somethings to be attr_accessible only those things can be accessed in console or by website Interface.

    eg: Suppose you made name and email to be attr_accessible:

    attr_accessible :name, :email
    

    and left out created_at and updated_at (which you are supposed to). Then you can only edit/update those fields in console.

    0 讨论(0)
  • 2020-12-10 06:11

    If you want to expose a field form your model, you can use

    attr_accessor :meth # for getter and setters
    attr_writer :meth # for setters
    attr_reader :meth # for getters
    

    or if you want add some behaviour to your attribute, you ll have to use virtual attributes

    def meth=(args)
     ...
    end
    def meth
     ...
    end
    

    cheers.

    0 讨论(0)
提交回复
热议问题