Dynamic URL -> Controller mapping for routes in Rails

后端 未结 4 925
死守一世寂寞
死守一世寂寞 2020-12-13 10:55

I would like to be able to map URLs to Controllers dynamically based on information in my database.

I\'m looking to do something functionally equivalent to this (ass

4条回答
  •  无人及你
    2020-12-13 11:51

    So I think that you are asking that if you have a Views table and a View model for it where the table looks like

    id | name | model
    ===================
    1  | aaa  | Post
    2  | bbb  | Post
    3  | ccc  | Comment
    

    You want a url of /aaa to point to Post.controller - is this right?

    If not then what you suggest seems fine assuming it works.

    You could send it to a catch all action and have the action look at the url, run the find_by_name and then call the correct controller from there.

    def catch_all
      View.find_by_name('aaa').controller.action
    end
    

    Update

    You can use redirect_to and even send the params. In the example below you I am sending the search parameters

    def catch_all
      new_controller = View.find_by_name('aaa').controller
      redirect_to :controller => new_controller, :action => :index, 
          :search => params[:search] 
    end
    

提交回复
热议问题