I’m new to ORM in general and I’m having trouble getting Rails to generate ok SQL. I have two tables, messages and users. Basically, I want a list of the messages with the user_name of the senders tacked on.
It would be great if:
-
I only got that one column from the user table (the user table has lots of columns that don’t need to get selected)
-
It used a LEFT JOIN (I want messages even if the users are gone for some reason, and I don’t want to slow things down with an INNER JOIN)
-
I don’t need to mention the names of the foriegn keys in this code (I should only have to set those up in the models and “NOT REPEAT MYSELF”, right?)
I have these models set up:
class Message < ActiveRecord::Base
belongs_to :sender, :class_name => "User", :foreign_key => "from_user_id"
belongs_to :recipient, :class_name => "User", :foreign_key => "to_user_id"
end
class User < ActiveRecord::Base
has_many :sent_messages, :class_name => "Message", :foreign_key => "from_user_id"
has_many :received_messages, :class_name => "Message", :foreign_key => "to_user_id"
end
I really WANT to like ORM, but it seems like it’s so easy to get to the point where you just have to write the queries yourself.
Perhaps something like this will do the trick (in Message model):
The thing is, that unless this join works as expected, you will need to specify the joins() with an SQL snippet, and then the includes() will probably NOT utilize this join, and rather do N+1 queries in total.