Colin Law wrote:
> Is there any advantage to this rather than the original solution (now
> simplified by the realisation that the second query does not need the
> :conditions spec)?  It is all done in one query, but both parts of the
> query will be executed even when the second part is not required, I
> think.
> 
> Colin

In my experience, SQL is always faster than Ruby. If you need to improve 
the performance of your Ruby application one easy way is to do fewer SQL 
calls and to get the SQL engine to do more of the work. One complex SQL 
call is almost always quicker than two or three simpler calls.

I expect the difference in performance between doing the one complex SQL 
call and just the first of Max's original statements (the case where 
that one returns a result, and therefore the second 'or' statement isn't 
called), is minimal. Unless your SQL call is particularly complex or 
poorly designed, its not SQL that slows the data retrieval in 
ActiveRecord.

However, the trade off is maintainability. Two or three simple steps are 
usually easier to write and easier to debug. They are also easier for a 
third party to understand.

So now it's Max's choice - best performance or more easily maintained. 
Personally, I'd go for his original solution, unless there was a 
performance issue.

Oh! and to maximise the maintainability, I'd recommend splitting the 
queries out to their own methods:

def last_state
  self.states.find(:first, :order => "created_at")
end

def first_state_after(time)
  self.states.find(:first, :conditions => ["created_at < ?", time],
:order => "created_at desc")
end

first_state_after(time) || last_state

-- 
Posted via http://www.ruby-forum.com/.

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to