I am new to both DBs and Rails (using 3.2), and I suspect this is a basic question that I’m just having trouble finding an answer for.
I’m making an app that tracks articles people submit to journals. So, each user has a number of articles. For each article, they can submit it to a number of journals. The submission object itself keeps track not only of the article being submitted and the journal it’s submitted to, but also the date it was submitted, the way it was submitted (email, online system, etc.), the date a response was received (if any), the response (if any) (e.g. accepted, resubmit, decline).
I’m trying to allow a user to view all of their outstanding submissions in one place. So, for each user, I’m trying to query the db to get all submissions belonging to articles that belong to that user, but only returning the submissions for which response is NULL (meaning there is no response yet, and thus the submission is still outstanding).
So my models are related like this:
class User < ActiveRecord::Base
has_many :articles
end
class Article < ActiveRecord::Base
belongs_to :user
has_many :submissions
end
class Journal < ActiveRecord::Base
has_many :submissions
end
class Submission < ActiveRecord::Base
belongs_to :article
has_one :journal
end
Now, for a given @user, I think I could do something like
@articles_with_subs = @user.articles.joins(:submissions)
and then
@out_subs = Array.new
@articles_with_subs.each do |article|
outs = article.submissions.where("response NOT NULL")
@out_subs.push outs
end
@out_subs.flatten!
but that seems pretty inefficient. What probably big, obvious thing am I missing?
Thanks very much.
1 Answer