usage of attr_accessor in Rails - ruby-on-rails

When do you use attr_reader/attr_writer/attr_accessor in Rails models?

Never, unless you have specific need for it. Automatic database-backed accessors are created for you, so you don't need to worry.
Any attr_accessors you do create will change the relevant #attr on the rails object, but this will be lost when the object is destroyed, unless you stick it back in the database. Sometimes you do want this behavior, but it's unusual in a rails app.
Now in ruby, it's a different story, and you end up using these very frequently. But I'd be surprised if you need them in rails---especially initially.

attr_accessor can be used for values you don't want to store in the database directly and that will only exist for the life of the object (e.g. passwords).
attr_reader can be used as one of several alternatives to doing something like this:
def instance_value
"my value"
end

Rails models are just ruby classes that inherit from ActiveRecord::Base. ActiveRecord employs attr_accessors to define getters and setters for the column names that refer to the ruby class's table. It's important to note that this is just for persistence; the models are still just ruby classes.
attr_accessor :foo is simply a shortcut for the following:
def foo=(var)
#foo = var
end
def foo
#foo
end
attr_reader :foo is simply a shortcut for the following:
def foo
#foo
end
attr_writer :foo is a shortcut for the following:
def foo=(var)
#foo = var
end
attr_accessor is a shortcut for the getter and setter while attr_reader is the shortcut for the getter and attr_writer is a shortcut for just the setter.
In rails, ActiveRecord uses these getters and setters in a convenient way to read and write values to the database. BUT, the database is just the persistence layer. You should be free to use attr_accessor and attr_reader as you would any other ruby class to properly compose your business logic. As you need to get and set attributes of your objects outside of what you need to persist to the database, use the attr_s accordingly.
More info:
http://apidock.com/ruby/Module/attr_accessor
http://www.rubyist.net/~slagell/ruby/accessors.html
What is attr_accessor in Ruby?

If you are using it to validate the acceptance of the terms_of_service, you should really consider using validates :terms_of_service, :acceptance => true. It will create a virtual attribute and is much more concise.
http://guides.rubyonrails.org/active_record_validations.html#acceptance.

One example is to have a number of options stored in one serialized column. Form builder would complain if you try to have a text field for one of these options. You can use attr_accessor to fake it, and then in the update action save it in the serialized column.

Related

ActiveRecord: Best way to add a 'fake' model class?

In our Rails application, the Post resource can be made by either a User or an Admin.
Thus, we have an ActiveRecord model class called Post, with a belongs_to :author, polymorphic: true.
However, in certain conditions, the system itself is supposed to be able to create posts.
Therefore, I'm looking for a way to add e.g. System as author.
Obviously, there will only ever be one System, so it is not stored in the database.
Naïvely attempting to just add an instance (e.g. the singleton instance) of class System; end as author returns errors like NoMethodError: undefined method `primary_key' for System:Class.
What would be the cleanest way to solve this?
Is there a way to write a 'fake' ActiveRecord model that is not actually part of the database?
There's two ways that I see that make the most sense:
Option A: Add a 'system' Author record to the DB
This isn't a horrible idea, it just shifts the burden onto you making sure certain records are present in every environment. But you can always create these records in seed files if you want to ensure they're always created.
The benefit over option B is that you can just use standard ActiveRecord queries to find all of the system's Posts.
Option B: Leave the association nil and add a new flag for :created_by_system
This is what I would opt for. If a Post was made by the system, just leave the author reference blank and set a special flag to indicate this model was created internally.
You can still have a method to quickly get a list of all of them just by making a scope:
scope :from_system, -> { where(created_by_system: :true) }
Which one you choose I think depends on whether you want to be able to query Post.author and get information about the System. In that case you need to take option A. Otherwise, I would use option B. I'm sure there's some other ways to do it too but I think this makes the most sense.
Finally I ended up with creating the following 'fake' model class that does not require any changes to the database schema.
It which leverages a bit of meta-programming:
# For the cases in which the System itself needs to be given an identity.
# (such as when it does an action normally performed by a User or Admin, etc.)
class System
include ActiveModel::Model
class << self
# The most beautiful kind of meta-singleton
def class
self
end
def instance
self
end
# Calling`System.new` is a programmer mistake;
# they should use plain `System` instead.
private :new
def primary_key
:id
end
def id
1
end
def readonly?
true
end
def persisted?
true
end
def _read_attribute(attr)
return self.id if attr == :id
nil
end
def polymorphic_name
self.name
end
def destroyed?
false
end
def new_record?
false
end
end
end
Of main note here is that System is both its own class and its own instance.
This has the following advantages:
We can just pass Post.new(creator: System) rather than System.new or System.instance
There is at any point only one system.
We can define the class methods that ActiveRecord requires (polymorphic_name) on System itself rather than on Class.
Of course, whether you like this kind of metaprogramming or find it too convoluted is very subjective.
What is less subjective is that overriding ActiveRecord's _read_attribute is not nice; we are depending on an implementation detail of ActiveRecord. Unfortunately to my knowledge there is no public API exposed that could be used to do this more cleanly. (In our project, we have some specs in place to notify us immediately when ActiveRecord might change this.)

Rails ActiveRecord non db attributes?

I've got an ActiveRecord model, Instance, which is based in the database, but has some non-database attributes.
One example is 'resolution'.
I need to be able to set/get the resolution, but this attribute needs custom non-db setters/getters. Where do I put these & how do I structure my model?
I also need to be able to validate resolutions as they are set via regex. Can I use validates_format_of or do I need to code a custom Validator?
If you need standard reader/writer methods, you can use attr_accessor:
class Instance
attr_accessor :resolution
end
You can also write the reader and writer method by yourself:
class Instance
def resolution
#resolution
end
def resolution=(value)
#resolution = value
validate! # this will raise RecordInvalid if the validation fails
end
end

Non persistent ActiveRecord model attributes

I want to add to an existing model some attributes that need not be persisted, or even mapped to a database column.
Is there a solution to specify such thing ?
Of course use good old ruby's attr_accessor. In your model:
attr_accessor :foo, :bar
You'll be able to do:
object.foo = 'baz'
object.foo #=> 'baz'
I was having the same problem but I needed to bootstrap the model, so the attribute had to persist after to_json was called. You need to do one extra thing for this.
As stated by apneadiving, the easiest way to start is to go to your model and add:
attr_accessor :foo
Then you can assign the attributes you want. But to make the attribute stick you need to change the attributes method. In your model file add this method:
def attributes
super.merge('foo' => self.foo)
end
In case anyone is wondering how to render this to the view, use the method arguments for the render method, like so:
render json: {results: results}, methods: [:my_attribute]
Please know that this only works if you set the attr_accessor on your model and set the attribute in the controller action, as the selected answer explained.
From Rails 5.0 onwards you could use attribute:
class StoreListing < ActiveRecord::Base
attribute :non_persisted
attribute :non_persisted_complex, :integer, default: -1
end
With attribute the attribute will be created just like the ones being persisted, i.e. you can define the type and other options, use it with the create method, etc.
If your DB table contains a matching column it will be persisted because attribute is also used to affect conversion to/from SQL for existing columns.
see: https://api.rubyonrails.org/classes/ActiveRecord/Attributes/ClassMethods.html#method-i-attribute
In my case I wanted to use a left join to populate custom attribute. It works if I don't add anything but I also want to be able to set the attribute on a new object and of course it doesn't exist. If I add attr_accessor then it always returns nil after a select. Here's the approach I've ended up with that works for setting on new object and retrieving from left join.
after_initialize do
self.foo = nil unless #attributes.key?("foo")
end
def foo
#attributes["foo"]
end
def foo=(value)
#attributes["foo"] = value
end

Rails3 timestamp mapping to legacy table

I have a legacy table with a column for the last update timestamp.
Now I do want to tell my model that the rails attribute updated_at is mapped to the legacy column.
alias_attribute :updated_at, :lastcall
Now I can access the column but it's not getting updated when i update the object.
So how can I use the rails timestamps with an legacy column?
Best,
P
Try to add this as well, which will alias the setter method.
alias_attribute :updated_at=, :lastcall=
I don't know if there's a 'proper' way of doing it, but you could do it with a before_save or before_update filter on the model.
class LegacyModel < ActiveRecord::Base
before_update :update_lastcall
private
def update_lastcall
self.lastcall = Time.now
end
end
If you don't want to get the model messy you could put it into an Observer.
I'd also like to draw your attention to this, if your timestamp column names are site-wide (as mine are). I didn't want to clutter up my models, and fortunately, you can monkey-patch ActiveRecord::Timestamp. I placed the below into a dir named lib/rails_ext/active_record.rb (I'm an organization freak) and called it with a require 'rails_ext/active_record' declaration in one of my initializers in config/initializers/.
module ActiveRecord
module Timestamp
private
def timestamp_attributes_for_update #:nodoc:
[:modified_time, :updated_at, :updated_on, :modified_at]
end
def timestamp_attributes_for_create #:nodoc:
[:created_date, :created_at, :created_on]
end
end
end
My custom attributes ended up being :modified_time and :created_date. You'd specify your :lastcall column in one of those (timestamp_attributes_for_update, I'm assuming). No mucking with your models required.

What is the best practices place to manipulate form data before saving in Rails 3?

From the pointview of rails best practices, what is the best place to manipulate form data before saving?
For instace, on a contact form, I want to make sure that all data is saved in capitalized form ( don't you hate when PEOPLE SHOUT AT YOU in their "please contact me" form submission? :-) )
is it better to do manipulation in controller? I could either do it in create, or move it into some sort of private method , that will capitalize all string attributes of the object before saving / updating?
Or
is it better do in the model before_save?
It makes sense to me that it should be done in the model since I probably want that to be the same for all records, no matter whether I manipulate on them in a rake task or through the web interface.
Bonus:
Also where would I place it if I want that that on ALL my models, with the ability to override default on a case by case basis? Application controller?
There might be some special cases where you want to save value without capitalizing - i.e. brand name products that don't capitalize (i.e. utorrent) or a last name that should have multiple caps in the name (i.e. Irish & Scottish names like McDonald)
Thank you!
the easiest place to put this is in your model. I would suggest using either before_save or even before_validation if you feel that fits better. Something like this would do the trick:
before_save :upcase_content
def upcase_content
self.content = self.content.upcase
end
Additionally if you wanted to allow for exceptions of a case by case basis you could add an attr_accessor to your model.
class MyModel < ActiveRecord::Base
attr_accessor :dont_upcase
before_save :upcase_content, :unless => :dont_upcase
...
end
then when you create a model set the accessor to true
#model = Model.new(:brand_name => utorrent)
#model.dont_upcase = true
#model.save!
The best place to put this is in your model, that way you have a fat model and a skinny controller, which is a "good thing".
If you want to have this be available for all of your models my suggestion is to use a module which contains your shared functionality and then include that in all the models you want to have the default behavior.
Ok based on the suggestions from other replies I came up with this solution:
lib/clean_strings.rb
module ActiveRecord
class Base
attr_accessor :dont_capitlize, :dont_strip
before_save :_capitalize_strings, :unless => :dont_capitlize
before_save :_strip_whitespaces, :unless => :dont_strip
def _capitalize_strings
self.attributes.each_pair do |key, value|
self[key] = value.capitalize if value.respond_to?('capitalize')
end
end
def _strip_whitespaces
self.attributes.each_pair do |key, value|
self[key] = value.strip if value.respond_to?('strip')
end
end
end
end
in environment.rb addded
require "clean_strings"
Now whenever I do
#a.dont_capitalize = true
#a.save!
it cleans it before saving according to my rules ( it will strip whitespace, but not capitalize it ). Obviously it needs more fine tuning, but i think it's a good way to define format rules for commonplace things. This way I don't need to sanitize every and each form input for things like extra whitespaces, or people who don't know where the CAPS LOCK is !!!
Thank you all for your input ( all upvoted).

Resources