← Back to Upcase

Display params in view

(Kate Daly) #1

I have a post model that has many tags through tagging. Tags are being handled in the posts controller:
if params[:tag]
@posts = Post.tagged_with(params[:tag]).order(“created_at DESC”).page(params[:page])
I would like to display the tag name above the posts, something like “Archives for tag name”.

I’ve tried the following in the view file:
<% if params[:tag] %>
<%= params %>
<% else %>
Viewing all posts

That renders {“controller”=>“posts”, “action”=>“index”, “tag”=>“metrics”} in the browser. My question is how do I display only the tag name (in this case “metrics”)?

(Pedro Moreira) #2


I don’t think you should be interacting with the params from the view. Your controller is passing a @posts object, so you could try to get the tags from that post, with @posts.tags. Hope this helps :slight_smile:

(Ben Orenstein) #3

Agreed with @pedromoreira.

(Kate Daly) #4

Thanks for the suggestions :slight_smile: That was my approach initially unfortunately I just don’t know how to make it work. I have tried the following:
<% if params[:tag] %>
<%= @posts.tags %> #=>undefined method `tags’ for ActiveRecord::Relation:0x007fbc36e92c68

In case relevant, the tagged_with is defined in the posts.rb:
def self.tagged_with(slug)

github repo is here: https://github.com/ksdaly/alex

I really appreciate your help!

(Pedro Moreira) #5

Glad to help :slight_smile:

The problem things to be that you are accessing a param that is not present. In your posts_controller, you are changing the @posts that get passed out to the view: if you have a “tag” or “category” param, you pass a different @posts object. But neither of these are ever present for the posts index action.

Maybe you could try to think of your “Archives for tag name” in terms of simple actions and create resources dedicated to building it, perhaps starting with the idea of a tag_archive_controller and building from there.