【问题标题】:Rails routing with models带模型的 Rails 路由
【发布时间】:2012-01-16 02:57:22
【问题描述】:

如何在我的 config/routes.rb 文件中使用模型?我想要完成的是以下路线。

match '/:name', :topic => Post.where(:topic => name).first, :to => 'posts#search'

这可能吗?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3.1 controller routes


    【解决方案1】:

    @Michael 是对的——不要将数据库代码放在路由文件中。当然,这是可能的,但它确实违反了 Rails 的约定和原则。

    更好的方法是:

    resources :posts do
      collection { get :search }
    end
    

    您的搜索表单如下所示:

    = form_tag(search_posts_path, :method => :get) do
      = text_input_tag(:q)
    

    还有你的控制器:

    def search
      @posts = Post.where("body like ?", "%#{params[:q]}%")
    end
    

    请注意,您通常也会使用分页(will_paginate 或 kaminari),并且可能需要考虑使用像 sphinx 这样的全文搜索引擎。

    【讨论】:

      【解决方案2】:

      路由是控制器而不是模型。另外,我建议不要将主题选择放在这样的路线中。大多数正确的轨道是在正确的区域做正确的事情。

      在我看来,标准和基于 REST 的系统通常是相同的,例如Posts 控制器通过 app/views/posts 中的视图管理 Post 模型的记录,但它们是不同的东西。

      有路由/:name 去posts#search 是可以的,但是我觉得获取相关主题应该在posts 控制器中完成。如果搜索在帖子中,您可以在路线上使用嵌套资源,例如:

      resources: :topics do
        resources :posts, :member => :search
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-07-23
        • 2016-01-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多