Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a virtual attribute to a model in Ruby on Rails?

I'm working on a RubyonRails/ActiveAdmin application. My RoR version is 4.2.5 and AA version is 1.0.0. I have a model Message as follows.

class Message < ActiveRecord::Base    belongs_to :user   validates :user, :content, presence: true    def palindrome     # return true/false   end  end 

As you see, I want to have a read-only attribute palindrome which only depends on the content of message. I want this attribute to be treated exactly like a normal attribute. By normal, I mean when I retrieve messages via rails console or request json format of messages, I want to see a palindrome attribute in the list. I would also like to have a filter for message by this attribute.

I'm not sure how could I achieve this.

like image 857
moorara Avatar asked Nov 16 '15 01:11

moorara


People also ask

What is a virtual attribute in rails?

What is 'Virtual Attribute'? The Virtual Attribute is a class attribute, which has no representation in the database. It becomes available after object initialization and remains alive while the object itself is available (like the instance methods).

What is virtual attribute in Ruby?

Ruby actually lets you create virtual attributes this way, which keeps you from having to manually create getter and setter methods as given below, attr_reader :title # getter. attr_writer :title # setter. attr_accessor :title # both getter and setter.

What are virtual attributes?

A Virtual Attribute is a type of AttributeTypes in which the Attribute Value are not actually stored in the Back-end but are rather dynamically generated in some manner. Virtual Attributes may or may NOT be part of the entry's defined ObjectClass Type and sometimes any ObjectClass Type.

What is Attr_accessible?

attr_accessible is used to identify attributes that are accessible by your controller methods makes a property available for mass-assignment.. It will only allow access to the attributes that you specify, denying the rest.


1 Answers

Ruby actually lets you create virtual attributes this way, which keeps you from having to manually create getter and setter methods:

attr_reader   :palindrome #getter attr_writer   :palindrome #setter attr_accessor :palindrome #both 

You can also pass multiple arguments too:

attr_accessor :palindrome, :foo, :bar 

The documentation for it isn't the greatest.

like image 78
Brent Eicher Avatar answered Oct 16 '22 08:10

Brent Eicher