在Rails中路由链接?

时间:2009-07-20 20:40:43

标签: ruby-on-rails

我正在Rails写一个会议列表网站,并遇到了这个要求:

链,无特定顺序,用于查找事件的URL,例如:

/英寸/:城市/上/:标签/带/:扬声器

或重新排列

/英寸/:城市/带/:扬声器/上/:标签

我可以逐一处理这些问题。有没有办法动态处理这些请求?

1 个答案:

答案 0 :(得分:0)

我用以下内容实现了它(原因是某些特定于应用程序的代码):

routes.rb中:

  map.connect '/:type/*facets', :controller => 'events', :action => 'facets'

events_controller.rb:

def facets
    @events = find_by_facets(params[:facets], params[:type])
    render :action => "index"

  end

application_controller.rb:

def find_by_facets(facets, type = nil)
query = type.nil? ? "Event" : "Event.is('#{type.singularize.capitalize}')"
for i in (0..(facets.length - 1)).step(2)
  query += ".#{facets[i]}('#{facets[i+1].to_word.capitalize_words}')"
end
@events = eval(query)

end

event.rb:

  named_scope :in, lambda { |city| { :conditions => { :location => city } } }

  named_scope :about, lambda {
      |category| {
          :joins => :category,
          :conditions => ["categories.name = ?", category]
      }
  }

  named_scope :with, lambda {
      |speaker| {
          :joins => :speakers,
          :conditions => ["speakers.name = ?", speaker]
      }
  }

  named_scope :on, lambda {
      |tag| {
          :joins => :tags,
          :conditions => ["tags.name = ?", tag]
      }
  }

  named_scope :is, lambda {
      |type| {
          :joins => :type,
          :conditions => ["types.name = ?", type]
      }
  }

这给了我像/ meetings / in / salt_lake_city / with / joe_shmoe或/ lectures / about / programming / with / joe_splo /这样的网址,没有特别的顺序。赢了!