What is the difference between a reference to object.id vs object [: id] when returning a model dataset?

Hi guys, busy learning ROR ... I was not sure how to look for this problem in stackoverflow, so sorry if this was asked before: p

Mostly I'm in the console environment busy reading all the rows from the table into a variable, and I noticed that you can reference the results by specifying my_object.idOR my_object[:id].

Can someone tell me if there is any specific reason? Is one of these "methods" obsolete or what is the reason for this?

Here is the code snippet: (if everything is installed)

my_object = MyModel.find(:all)
my_object[1].id #returns => 'my value'
my_object[1][:id] # also returns => 'my value'

Which of these methods is best practice? Or is this purely a preference for notation?

Thank:)

+3
3

my_object[1].id

"id" - , MyModel, "id =" setter (, )

my_object[1][:id] or my_object[1]["id"] 

@attributes:

    def read_attribute(attr_name)
      attr_name = attr_name.to_s
      if !(value = @attributes[attr_name]).nil?
      ......
    end

,

def [](attr_name)
   read_attribute(attr_name)
end

my_object[1][:id]

[], , , :

my_object[1][](:id)

, Ruby , , ( , php, js ..), .

+2

read_attribute, , . ActiveRecord::Base:

# Returns the value of the attribute identified by <tt>attr_name</tt> after it has been typecast (for example,
# "2004-12-12" in a data column is cast to a date object, like Date.new(2004, 12, 12)).
# (Alias for the protected read_attribute method).
def [](attr_name)
  read_attribute(attr_name)
end

model.attribute - . [], , , .

+1

I would use model.attribute, it has become more standard and allowed you flexibility if you need to override it:

u = User.first
u.identity_url
=> nil
class &lt&lt u
  def identity_url
    read_attribute(:identity_url) || "undefined"
  end
end
=> nil
u.identity_url
=> "undefined"
u[:identity_url]
=> nil

Kind of a lame example, but you get the idea.

0
source

Source: https://habr.com/ru/post/1736311/


All Articles