我在Rails中创建了一个在线投资组合,其中包含不同的项目。我希望能够通过关键字过滤项目。我的方法是为ProjectsController中的每个关键字定义一个方法,并链接关键字以调用方法。
示例关键字= graphic_design:
<%= link_to 'Graphic Design', :action => "filter_"+@project.keyword.to_s %>
这样我就得到了错误:
Couldn't find Project with ID=filter_graphic_design
这对我来说非常明显。我的问题:有没有办法告诉routes.rb只为'filter_'方法表现不同?还有其他建议吗?
答案 0 :(得分:1)
我认为这样的事情可以起作用
map.connect "/projects/filter_{filter}", :controller => 'projects', :action => 'filter'
虽然没有尝试过
答案 1 :(得分:1)
你的做法是错误的。为什么首先需要为每个关键字设置filter_方法?它非常简单的解决方案。首先在routes.rb中定义一个命名路由:
map.filter '/projects/:filter_this_for_me', :controller => 'projects', :action => 'filter'
在你的观点中,
<%= link_to 'Graphic Design', filter_path("filter_" + @project.keyword.to_s) %>
在过滤器操作中,
def filter
logger.info("Parameters that is being received: #{params}")
filter_what = params[:filter_this_for_me]
if(!filter_what.nil? && !filter_what.blank?)
# Here filter_what will have "filter_graphic_design" or "filter_something"
# With which you can filter any data that you want.
# Filter your projects here.
end
end