In Ruby on Rails, why will story.votes return an empty Array object, but story.votes.create will actually invoke a method of the Vote class?
In Ruby on Rails, say a Story object can "has_many" Vote objects (a story is voted "hot" by many users).
So when we do a
s = Story.find(:first)
s
is a Story object, and say
s.votes
returns []
and
s.votes.class
returns Array
So clearly, s.votes is an empty Array object.
At this time, when
s.votes.creat开发者_JAVA技巧e
is called, it actually invokes a method of the Vote class? How come an Array class object can invoke a Vote class method?
In your case, .votes
is not returning an Array
, it's returning a special Association
object.
The reason it looks like an Array
is because the association object delegates all of its methods except for the dynamic ones like create
to an array object it holds internally. And, this means that when you call .class
on the object, that also gets delegated to the Array object.
votes
is not an array, it's a method of a Story
object. If you call it alone, it returns an array of all Vote
records associated with that Story
. The reason you are given Array
when you do s.votes.class
is that s.votes
is returning an array (which in this case is empty because s
has no votes) and you're checking the class of the returned array.
In turn, s.votes.create
is another method dynamically generated by Rails based on your model associations. It's not a method of Array
.
精彩评论