Rails-如何将多个Controller动作合并为一个动作?

时间:2018-07-11 22:04:58

标签: ruby-on-rails activerecord routes ruby-on-rails-5 ancestry

我当前正在使用Ancestry,并试图显示URL中对象的层次结构,但是它们都来自同一模型,并且应该为每个对象呈现相同的html。

这是我的路线:

get ':location', to: 'locations#show', as: :location
get ':location/:location_child', to: 'locations#show_child', as: :location_child
get ':location/:location_child/:location_grandchild', to: 'locations#show_grandchild', as: :location_grandchild
get ':location/:location_child/:location_grandchild/:location_greatgrandchild', to: 'locations#show_greatgrandchild', as: :location_greatgrandchild

这是匹配的Controller动作。它们都呈现相同的html页面,但是有没有一种方法可以更好地清理我的路线和动作,使其更加合理呢?

  def show
    @location = Location.find_by_slug(params[:location])
  end

  def show_child
    @location = Location.find_by_slug(params[:location_child])
    render "show"
  end

  def show_grandchild
    @location = Location.find_by_slug(params[:location_grandchild])
    render "show"
  end

  def show_greatgrandchild
    @location = Location.find_by_slug(params[:location_greatgrandchild])
    render "show"
  end

在此先感谢您的帮助。

0 个答案:

没有答案