Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to make Rails ActiveRecord attributes private?

By default, ActiveRecord takes all fields from the corresponding database table and creates public attributes for all of them.

I think that it's reasonable not to make all attributes in a model public. Even more, exposing attributes that are meant for internal use clutters the model's interface and violates the encapsulation principle.

So, is there a way to make some of the attributes literally private?

Or, maybe I should move on to some other ORM?

like image 619
Leonid Shevtsov Avatar asked Sep 21 '10 22:09

Leonid Shevtsov


People also ask

Can you use ActiveRecord without rails?

One of the primary aspects of ActiveRecord is that there is very little to no configuration needed. It follow convention over configuration. ActiveRecord is commonly used with the Ruby-on-Rails framework but you can use it with Sinatra or without any web framework if desired.

What is ActiveRecord in Ruby on Rails?

Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.

What are rails attributes?

In Rails 5, model attributes go through the attributes API when they are set from user input (or any setter) and retrieved from the database (or any getter). Rails has used an internal attributes API for it's entire lifetime. When you set an integer field to “5”, it will be cast to 5.


2 Answers

Jordini was most of the way there

Most of active_record happens in method_missing. If you define the method up front, it won't hit method_missing for that method, and use yours instead (effectively overwriting, but not really)

class YourModel < 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 
like image 158
Matt Briggs Avatar answered Sep 19 '22 18:09

Matt Briggs


well, you could always override the methods...

class YourModel < ActiveRecord::Base    private    def my_private_attribute     self[:my_private_attribute]   end    def my_private_attribute=(val)     self[:my_private_attribute] = val   end  end 
like image 34
jordinl Avatar answered Sep 20 '22 18:09

jordinl