So I have an example I came across in some reading where we define in a rails model
has_many :some_tablename
Then later they reference it by saying
if some_tablename.empty?
#do something
end
I am new to Ruby, so the magic isn’t quite clear to me why I wouldn’t do
if :some_tablename.empty?
#do something
end
Now, I understand that .empty can be called on a number of types, Symbol not being one of them. So, I am expecting that the answer is going to be something like….the .inspect or .to_s is being called on the symbol :some_tablename (behind the scenes) and returning a string representation which then we’re calling .empty on it.
is that correct, or can someone set me straight of how it is lining up :some_tablename to some_tablename?
ActiveRecord makes extensive use of Ruby as a metaprogramming language to perform much of the queries you can make over a model.
When you call
if some_tableyou are calling asome_tablemethod which in fact does’t exists, so themethod_missingmethod ofActiveRecord::Baseis called (if your model extends it) and it looks in an attributes hash which is built with yourhas_many,belongs_todirectives and then builds a query over that missing method, specifically an inner join in your case assome_tableis ahas_many.Check http://apidock.com/rails/ActiveRecord/Base/method_missing.