Re:What ORMs have taught me: just learn SQL (2014)
by james-mcelwain on Friday September 20, 2019 @10:38PM
(#21033150)
> What if your result set doesn't really match any of your models? Pick one arbitrarily.
I don't want to sound like the ORM defender, but I'm not sure I understand.
This sounds like a deficiency of Ruby and the ActiveRecord record model. In Java, for example, you'd just write a new POJO for your query, which isn't exactly difficult. There are no "smart methods" or whatever.
It is a valid criticism that this can proliferate data classes, but that depends on the application.
Re:What ORMs have taught me: just learn SQL (2014)
by philwelch on Saturday September 21, 2019 @04:00AM
(#21034082)
I was writing in terms of what I actually understand and have used—which doesn’t include any Java ORM. In fact if there are Java ORMs that consist solely of POJOs which are populated by raw SQL queries, I would gladly use them!
Re:What ORMs have taught me: just learn SQL (2014)
by slicebo123 on Sunday September 22, 2019 @07:44PM
(#21044743)
You can execute a "non-model" query like so:
results = ActiveRecord::Base.connection.execute(sql)
Re:What ORMs have taught me: just learn SQL (2014)
by philwelch on Saturday September 28, 2019 @02:29PM
(#21102021)
The API docs don’t make it clear whether that’s still possible so I didn’t mention it explicitly, but I have done that before and that’s what I was alluding to with the “array of hash tables” comment.
In ActiveRecord, there's a method called find_by_sql. You can't call it directly; it's a class method on an ActiveRecord model. So you have to choose which of your ActiveRecord models should be used to instantiate the rows of your result set. (What if your result set doesn't really match any of your models? Pick one arbitrarily.) Your SQL has some extra columns. What happens to the data in those columns? They get monkey-patched onto the individual objects. (Which is stupidly expensive in Ruby.) Other than that, the individual objects are fine. They even have all your smart instance methods, which may or may not behave properly with all the ad-hoc monkey patching.
If you tried to short-circuit all of that nonsense, you tend to get arrays of hash tables. Which is, in my opinion, already a perfectly adequate interface!