The is something I wrestle with a bit when I construct joined queries…
Perhaps some experienced insight will straighten this out for me.
Say you have two tables with two models, ‘authors’ and ‘posts’.
an author has_many posts, a post has_one author.
You need methods to do the following queries:
find_author(postid)
find_posts(authorid)
And you are doing a custom join query for both. How do you decide what
model they go into? To me either can make sense, so I am uncomfortable
with
picking one.
And you are doing a custom join query for both. How do you decide what
model they go into? To me either can make sense, so I am uncomfortable with
picking one.
What sort of custom join queries?
It seems that post.author and author.posts, the builtin association
methods,
are just the ticket.
Hmm… You make sense. When I first started I didn’t really understand
things and so I was doing something like:
find_by_sql(“SELECT * FROM authors,posts WHERE authors.id =
posts.authorid”)
But you’re right I can just do an association can’t I?
Is there no extra overhead to doing the association? I’ve read about
inefficiencies with Rails queries (ie. generating many unnecessary
queries)… Maybe that was in a many to many situation. Maybe I’m being
a
bit paranoid.
queries)… Maybe that was in a many to many situation. Maybe I’m being a
bit paranoid.
maybe there is an extra overhead, maybe not… if you are a SQL freak
(like
me ) the way to know it is watching the log, if both methods work for
you. If you are in Linux/UNIX flavored, you can tail -f
log/development.log
(or production.log or server.log, as your project runs).
Probably MySQL will be more/less (but never equally) optimized than
PostgreSQL, according to the engine’s way to get the data.
Say you have two tables with two models, ‘authors’ and ‘posts’.
an author has_many posts, a post has_one author.
A post belongs_to author would be the right way.
You need methods to do the following queries:
find_author(postid)
find_posts(authorid)
And you are doing a custom join query for both. How do you decide what
model they go into? To me either can make sense, so I am uncomfortable with
picking one.
Hmm… You make sense. When I first started I didn’t really understand
things and so I was doing something like:
find_by_sql(“SELECT * FROM authors,posts WHERE authors.id = posts.authorid”)
But you’re right I can just do an association can’t I?
Is there no extra overhead to doing the association? I’ve read about
inefficiencies with Rails queries (ie. generating many unnecessary
queries)… Maybe that was in a many to many situation. Maybe I’m being a
bit paranoid.
If you want to avoid the extra queries you can use :include option so it
gets all the data on just one query.