我有一个侧边栏,其中包含一系列帖子。我需要侧边栏上的相应帖子才能有一个活跃的课程。我目前没有工作,所以最好的方法是什么?
def is_active?(path)
current_page?(path) ? "active" : ""
end
<% @posts.each do |post| %>
<%= link_to post.title, post, class: is_active?(posts_path) %>
<% end %>
答案 0 :(得分:0)
正如我在评论中所说,以?
结尾的方法应该返回一个布尔值。如果你决定违反惯例,这将使我们更加困难。
我建议您实际使用active_link_to
,就像question中所解释的一样。
然而,主要问题是您没有为每个帖子正确生成URL:
IS_ACTIVE?(posts_path)
posts_path
是索引的路径,而不是单个帖子资源。你应该使用类似post_path(post)
你想做这样的事情:
首先是你的is_active?
方法,因为它有一个?应该返回一个布尔值
def is_active?(path)
current_page?(path)
end
然后您可以这样使用它(您需要使用post_path(post)
帮助程序获取帖子的URL)
<% @posts.each do |post| %>
<%= link_to post.title, post, class: ('active' if is_active?(post_path(post))) %>
<% end %>
编辑:因为is_active?和current_page一样吗?你应该简单地用别名声明替换is_active?
代码
alias :is_active? current_page?
答案 1 :(得分:0)
我必须在几年前开发出这样的解决方案。我实现了以下作为帮助方法来检测活动链接。请注意,这不是我认为的最佳解决方案。我必须提供一个完整的网址。可以自由编辑代码以使用路径或参数哈希。
# Returns true or false if the page is displayed that belongs to the given url.
def link_selected?(url)
request_method = request.method.to_sym
begin
url_params = Revolution::Application.routes.recognize_path(
url, {:method=>request_method}
)
rescue Exception => e
{}
end
begin
request_params = Revolution::Application.routes.recognize_path(
request.url, {:method=>request_method}
)
rescue
{}
end
return true if url_params == request_params
return false
end
def is_active?(url)
return link_selected?(url) ? 'active' : nil
end