0

I have this rails logic that uses partial SQL query code. I was wondering if there was a way a better way or a cleaner way to do the same thing (i.e. use rails's methods to replace the SQL code)?

@servers = Server
    .select("*", "(SELECT AVG('reviews'.'average') FROM 'reviews' WHERE 'reviews'.'server_id' = 'servers'.'id') AS s_avg")
    .order("s_avg DESC")
    .paginate(:page => params[:page], :per_page => 25)

1 Answer 1

2

First good thing is to move that code from view or controller to model and wrap it in scope. Moreover, scopes can be chained.

class Server < ActiveRecord::Base
  scope :averaged, -> { where(SQL CODE HERE) }
  scope :expensive, -> { where('price > ?', price) }
  scope :latest, -> { where('created_at > ?', Date.today - 3.days.ago) }
  scope :active, -> { where(active: true) }
end

Only then you can pass and chain it in controller:

@servers = Server.latest.averaged

So, simply try to brake your SQL on several parts, move these parts to model and wrap them with scopes. You can find a lot of useful examples of query methods without pure SQL here: http://guides.rubyonrails.org/active_record_querying.html

Sign up to request clarification or add additional context in comments.

2 Comments

Note: new scope will conflict with Object.new. I usually go for latest. Apart from that, good suggestion!
Chained scopes will undoubtedly be the way to go with this one

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.