link_to passing paramater and display problem - tag feature - Ruby on Rails
Posted
by bgadoci
on Stack Overflow
See other posts from Stack Overflow
or by bgadoci
Published on 2010-04-15T02:36:16Z
Indexed on
2010/04/15
2:43 UTC
Read the original article
Hit count: 578
I have gotten a great deal of help from KandadaBoggu on my last question and very very thankful for that. As we were getting buried in the comments I wanted to break this part out.
I am attempting to create a tag feature on the rails blog I am developing. The relationship is Post has_many :tags and Tag belongs_to :post. Adding and deleting tags to posts are working great.
In my /view/posts/index.html.erb I have a section called tags where I am successfully querying the Tags table, grouping them and displaying the count next to the tag_name (as a side note, I mistakenly called the column containing the tag name, 'tag_name' instead of just 'name' as I should have) . In addition the display of these groups are a link that is referencing the index method in the PostsController. That is where the problem is.
When you navigate to /posts you get an error because there is no parameter being passed (without clicking the tag group link). I have the .empty? in there so not sure what is going wrong here. Here is the error and code:
Error
You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.empty?
/views/posts/index.html.erb
<% @tag_counts.each do |tag_name, tag_count| %>
<tr>
<td><%= link_to(tag_name, posts_path(:tag_name => tag_name)) %></td>
<td>(<%=tag_count%>)</td>
</tr>
<% end %>
PostsController
def index
@tag_counts = Tag.count(:group => :tag_name, :order => 'updated_at DESC', :limit => 10)
@posts=Post.all(:joins => :tags,:conditions=>(params[:tag_name].empty? ? {}:
{ :tags => { :tag_name => params[:tag_name] }}
)
)
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @posts }
format.json { render :json => @posts }
format.atom
end
end
© Stack Overflow or respective owner