Accessing model properties in Rails

12,189

Solution 1

I would hesitate to override the attributes, and instead add to the model like this:

def titled_name
    "#{title} #{name}"
end

However, you can access the fields directly like this:

def name
    "#{title} #{self[:name]}"
end

Solution 2

You can create virtual attributes within your model to represent these structures.

There is a railscast on this very subject but in summary you can do something like this in your model

def full_name
  [first_name, last_name].join(' ')
end

def full_name=(name)
  split = name.split(' ', 2)
  self.first_name = split.first
  self.last_name = split.last
end

If you wish to explicitly change the value of an attribute when reading or writing then you can use the read_attribute or write_attribute methods. (Although I believe that these may be deprecated).

These work by replacing the accessor method of the attribute with your own. As an example, a branch identifier field can be entered as either xxxxxx or xx-xx-xx. So you can change your branch_identifier= method to remove the hyphens when the data is stored in the database. This can be achieved like so

def branch_identifier=(value)
  write_attribute(:branch_identifier, value.gsub(/-/, '')) unless value.blank?
end
Share:
12,189
Malik Daud Ahmad Khokhar
Author by

Malik Daud Ahmad Khokhar

Interested in React, Node.js, Hyperledger Fabric/Composer, docker.

Updated on June 05, 2022

Comments

  • Malik Daud Ahmad Khokhar
    Malik Daud Ahmad Khokhar almost 2 years

    So basically I have a controller. something like this

    def show
     @user = User.find[:params[id]]
     #code to show in a view
    end
    

    User has properties such as name, address, gender etc. How can I access these properties in the model? Can I overload the model accesser for name for example and replace it with my own value or concatenate something to it. Like in the show.html.erb view for this method I might want to concatenate the user's name with 'Mr.' or 'Mrs.' depending upon the gender? How is it possible?

  • Malik Daud Ahmad Khokhar
    Malik Daud Ahmad Khokhar over 14 years
    I need these in the model. I know how to get them in the view.
  • Jamie Hale
    Jamie Hale over 14 years
    Might want to be careful doing that as it could confuse the interface. Might be odd doing name = "Joe" and getting back "Mr. Joe".
  • John Topley
    John Topley over 14 years
    Those dollars should be hashes.
  • Sarah Mei
    Sarah Mei over 14 years
    Not to mention, this code only works if your user base contains no single ladies. ;)
  • DanSingerman
    DanSingerman over 14 years
    @Sarah, ah, you are quite right, I will do a fix for it. @Jamie - yes I agree, hence the caveat that is in my answer.
  • Mohammad AbuShady
    Mohammad AbuShady over 9 years
    Wouldn't the second code block fall into a recursive call and crash?