TopChef
TopChef

Reputation: 45513

Working with models in Ruby on Rails

  1. I have a table (posts) with a column called 'tag' I want to be able to call a particular set of tagged posts (Sports, Arts & Entertainment, etc) so that when a user clicks on the corresponding links, they only get posts from that category.

Here is what I have tried to implement so far: (in my posts model)

def self.seperate_by_tag
    @tag = find(:all, :tag => ??)
end

I'm assuming I need to input some sort of parameter into the :tag portion in order to access a set of posts with a particular tag, however, I'm not sure how to go about doing so.

  1. I also am having trouble with displaying posts in the order they are posted (i'd like them to be at the top).

    def self.find_posts
        find(:all, :order => ??) 
    end
    

Any help would be much appreciated!

Upvotes: 0

Views: 138

Answers (1)

Jordan Running
Jordan Running

Reputation: 106087

If your tag column is just text, then it would be as simple as this:

class Post < ActiveRecord::Base
  scope :by_tag, lambda {|tag_name| where :tag => tag_name }
end

# Usage:
Post.by_tag('Sports').all # => collection of posts

Using scope is covered in this Rails Guide.


As for your other question, as long as your posts table has a created_at column (provided with the timestamps migration helper, then you can order them reverse-chronologically (newest first) like so:

Post.order('created_at DESC').all

order is covered in this guide.


P.S. As you might have gathered from my code, the SomeModel.find :all, ... syntax is officially deprecated. You should instead use SomeModel.all, SomeModel.first, etc.

Upvotes: 2

Related Questions