简体   繁体   中英

Private/protected accessors to attributes in Rails 4

Supose that I have the following class:

class Foo < ActiveRecord::Base
    belongs_to :bar
end

In rails console I can do this:

foo = Foo.new
foo.bar_id = 3

But this can violates the encapsulation principle. I think that is better idea do:

foo = Foo.new
foo.bar = Bar.find(3);

And bar_id should be private/protected. This has nothing to do with the mass assignment and strong parameters but it is an security issue too.

Is there any way to set to private some attributes?

Is there a way to make Rails ActiveRecord attributes private?

class MyModel < ActiveRecord::Base

  private

  def my_private_attribute
    self[:my_private_attribute]
  end

  def my_private_attribute=(val)
    write_attribute :my_private_attribute, val
  end
end

I don't think just making the write accessor private or protected will reliably prevent change via update_attribute or mass assignment.

While it's not actually "private" per se, but you could get the desired effect by setting the attribute read_only, eg

attr_readonly :bar_id

and if you do need to update the value "private-ly," access it as @bar_id. Per the docs, "Attributes listed as readonly will be used to create a new record but update operations will ignore these fields."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM