What is the difference between activerecord's attribute and read_attribute?

StackOverflow https://stackoverflow.com/questions/23597789

  •  20-07-2023
  •  | 
  •  

سؤال

I'm able to run both and it returns the same vale:

user = User.new(name:'John')
user.attributes['first_name']
=> 'John'
user.read_attribute('first_name')
=> 'John'

Is one more performant than the other? Are there cases where I would use one over the other?

Thanks!

هل كانت مفيدة؟

المحلول

attributes returns a hash of all attributes for the user and ['first_name'] just accesses the specified parameter of the hash, whereas read_attribute just returns the single parameter asked for. You don't really need either of those methods to access the name as this can be done which makes the code a lot cleaner:

user = User.new(name:'John')
user.name
=> 'John'
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top