Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing model properties in Rails

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?

like image 519
Malik Daud Ahmad Khokhar Avatar asked Aug 20 '09 10:08

Malik Daud Ahmad Khokhar


2 Answers

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
like image 75
Magnar Avatar answered Oct 11 '22 23:10

Magnar


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
like image 20
Steve Weet Avatar answered Oct 12 '22 00:10

Steve Weet