1

I can't find any references to explain what the difference is between these two definitions. What is the purpose of using these two definitions like this?

def user_name=(name)
  user= User.where(:name => name)
  if user           
    self.user_id = user.id
  else              
    errors[:user_name] << "Invalid name entered"
  end               
end                 

def user_name       
  User.find(user_id).name if user_id
end                 
markhorrocks
  • 1,199
  • 19
  • 82
  • 151

2 Answers2

1

First one (with = sign) is the attribute setter and second one is attribute getter.

Using the setter, you are setting a value to an attribute where as you are retrieving that value using getter.

Trying to learn / understand Ruby setter and getter methods

http://tmonrails.wordpress.com/2009/08/05/ruby-setter-and-getter-methods/

Community
  • 1
  • 1
HungryCoder
  • 7,506
  • 1
  • 38
  • 51
0

Its how you write getters/setters in Ruby. Here's how the same looks like in Java:

// Java:                                |  // Ruby:
                                        |
public void setUserName(String name) {  |  def user_name=(name)
  ...                                   |    ...
}                                       |  end
                                        |
public String getUserName() {           |  def user_name
  ...                                   |    ...
end                                     |  end

So basically what the above code does is,

def user_name=(name)
  # Check if the user with given user_name exists
  # If it exists, then set the user_id to that user
  # Otherwise mark an error
end                 

def user_name
  # Find the user with current user_id and return their name
end
Subhas
  • 14,290
  • 1
  • 29
  • 37