TopChef
TopChef

Reputation: 45453

Displaying Posts by Tag - Ruby on Rails Blog

I have a Rails blog coming along quite nicely. However, I cannot seem to get my tagged articles to show up within their own page (for example, I'd like ONLY the articles tagged Arts & Entertainment to show up when that link is clicked).

I have a column in my scaffold model entitled tags. It takes a string. So

1) How do I go about accessing ONLY a specific tag? I tried something like the following:

def self.sports
    find(:all, :tags => 'gainmuscle')
end

to no avail.

2) How do I get them to show up in the view?

Any help would be very much appreciated.

Upvotes: 1

Views: 661

Answers (3)

alony
alony

Reputation: 10823

1) here you could use the scope in the model:

class YourModel < ActiveRecord::Base

  scope :by_tag, lambda{|tag| where(:tag => tag)}

  ...
end

And then in controller:

  @collection = YourModel.by_tag("gainmuscle")

2) I would say the best way is to create a partial with html code for 1 single post, and then render it this way:

  render :partial => 'post', :collection => @collection

(You can check partials usage here: http://apidock.com/rails/ActionView/Partials)

Upvotes: 1

AllanNorgaard
AllanNorgaard

Reputation: 284

Just to mention another approach; there are quite a few gems to deal with this exact purpose. This might be interesting, and personally I can vote for acts_as_taggable_on. This gives you quite a lot of options which might come in handy later on as well.

Upvotes: 0

Mithun Sasidharan
Mithun Sasidharan

Reputation: 20920

You can probably define a method inside your controller something similar to this :

def self.tagged_with
  @articles = Article.tagged(params[:tag]).paginate(default_paginate_options)
end

Here tagged is a namedscope. you can neglect that but the action generates all the articles which are tagged with the tag selected as :param. Tag is an attribute of the model Article in this case.

Upvotes: 1

Related Questions