【发布时间】:2023-04-06 11:07:02
【问题描述】:
我在最后一个问题上从 KandadaBoggu 那里得到了很多帮助,对此我非常感谢。当我们被埋在 cmets 中时,我想打破这部分。
我正在尝试在我正在开发的 rails 博客上创建一个标签功能。关系是 Post has_many :tags 和 Tag belongs_to :post。在帖子中添加和删除标签效果很好。
在我的 /view/posts/index.html.erb 中有一个名为 tags 的部分,我在其中成功查询了 Tags 表,对它们进行分组并在 tag_name 旁边显示计数(作为旁注,我错误地将包含标签名称的列,'tag_name' 而不是我应该有的'name')。此外,这些组的显示是一个链接,它引用 PostsController 中的 index 方法。这就是问题所在。
当您导航到 /posts 时,您会收到一个错误,因为没有传递参数(没有单击标签组链接)。我有.empty?在那里所以不确定这里出了什么问题。这是错误和代码:
错误
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
【问题讨论】:
标签: ruby-on-rails ruby