SuperString
SuperString

Reputation: 22529

Rails: scope order question

I have some posts that belongs to location and category, sort of like craigslist post.

I want to order by most recently posted and also filter by location and category if those are specified by the user.

Can someone give an example/hints on how to do this?

Upvotes: 2

Views: 5379

Answers (2)

Jesse Wolgamott
Jesse Wolgamott

Reputation: 40277

In Rails 3 you can change together orders, wheres and more. ASCICasts on activerecord queries in Rails3

query = Post.order("published_at desc")
query = query.where("location_id = ?", params[:location_id]) unless params[:location_id].blank?
query = query.where("category_id = ?", params[:category_id]) unless params[:category_id].blank?
@posts = query.all

Upvotes: 4

scragz
scragz

Reputation: 6700

You can cache the field you would use to sort be category and location into the post.

before_save: cache_sortables

def cache_sortables
  self.category_title = self.category.title if self.category?
  self.location_title = self.location.title if self.location?
end

Post.find(:all, :order => 'location_title, category_title, created_at')

It is left as an exercise to the reader to update the posts when the parent category/location title changes.

Upvotes: 0

Related Questions