Rails 这里的 Router 应该怎么写?

zhangsm · December 27, 2014 · Last by zhangsm replied at December 27, 2014 · 1689 hits

大家好,最近我在写一个小博客。遇到一些问题,不知道怎么写代码?想请教下。

文件routes.rb中:

 # 'rake db:migrate' 之前会检查; 新增节点后,要重启
Node.all.each do |node|
    get "articles/node/#{node.slug}", as: "articles_#{node.slug}", to: "articles##{node.slug}"
end

文件articles_controller.rb中:

Node.all.each do |node|
    name = node.slug
    define_method(name) do
        @articles = Article.send(name.to_sym).includes(:node).paginate(page: params[:page], per_page: 6)
        render action: 'index' and return
    end
end

上面的 Router 应该怎么写?

不知道社区里有没有人做过类似的需求,如果社区里有类似的帖子,可以给出链接。 谢谢!

可以使用 freindly_id 这个 gem, 网址 https://github.com/norman/friendly_id

# routes.rb
resources :articles do
  collection do
    get 'node/:slug', to: 'articles#node', as: :node
  end
end
# articles_controller.rb
def node
  @node = Node.find_by(slug: params[:slug])
  @articles = @node.articles.paignate(page: params[:page])
  render :index
end
You need to Sign in before reply, if you don't have an account, please Sign up first.