0

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?

Cristhian Boujon
  • 4,060
  • 13
  • 51
  • 90

2 Answers2

0

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
Community
  • 1
  • 1
Seb Wilgosz
  • 1,240
  • 15
  • 24
0

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, e.g.

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."

Tom Wilson
  • 797
  • 9
  • 26