Rails already has getters and setters without me setting an attr_accessor. How do I stop all setters ?

StackOverflow https://stackoverflow.com/questions/12921459

  •  07-07-2021
  •  | 
  •  

Question

Here is my class, as you can see, no attr_accessor

class LegacyBlogPost < ActiveRecord::Base
  establish_connection Rails.configuration.database_configuration['blogs']
  self.table_name = 'blogpost'
  self.primary_key = 'post_id'
end

But I can still read and write all variables. Is this default behavior ?

x = LegacyBlogPost.find(172925)
x.title += "."
x.save
=> true

My main question though, is how do I avoid ever writing to this class ? I understand I could make the mysql user only be allowed to do select statements. Also I belive I could re-write the rails setters to just return as soon as the method is hit. But I had assumed if I just set attr_reader's for everything, the writers just wouldn't be there.

Was it helpful?

Solution

ActiveRecord automatically creates getters\setters to read\write for all columns

If you want to make the model a read only do

class LegacyBlogPost < ActiveRecord::Base
  def readonly?
    return true
  end
end

To prevent it from being destroyed you can use

def before_destroy
  raise ActiveRecord::ReadOnlyRecord
end

credit http://blog.zobie.com/2009/01/read-only-models-in-activerecord/

OTHER TIPS

Look into using attr_accessible.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top