Rails - 根据数据库记录动态生成多个页面

时间:2017-04-01 21:58:25

标签: ruby-on-rails

我有一个rails应用程序,我需要遍历数据库中的记录,并将它们与同一数据库中的记录匹配,然后呈现一个页面,其内容基于URL中的字词。

想象一下,我们有这个数据库:

1 Basketball
2 Soccer
3 Baseball
4 Swimming

我需要构建一个为每个生成页面的函数:

domain.com/basketball-soccer
domain.com/basketball-baseball
domain.com/basketball-swimming
domain.com/soccer-baseball
domain.com/soccer-swimming
domain.com/baseball-swimming

这不应该为篮球和篮球等生成页面,如果它为篮球足球生成页面,那么足球篮球页面

还有像domain.com/basketball-cricket这样的页面,因为cricket没有在数据库中列出

内容应如何在每个页面上显示的示例: 这个页面是为了一场篮球/足球比赛。

寻找有关入门的建议或资源。我不确定是否可以像这样动态生成页面。我不想单独构建这些页面。

2 个答案:

答案 0 :(得分:0)

您可以在路线中使用正则表达式。将其放入routes.rb

match '/:regex', to: 'your_controller#your_action', constraints: {regex: /[a-zA-Z]+-[a-zA-Z]+?/}, via: :get

然后在您的控制器中,您将获得一个名为regex的参数,您可以使用params[:regex]访问该参数并正确处理。

答案 1 :(得分:0)

您可以使用通配符(catch all)路由,然后处理控制器内的所有逻辑。例如:

# routes.rb
# put this as the last route in the file
get '*url_pair', to: 'examples#show'

# examples_controller.rb
def show
  # get both values into an array, and sort into alphabetical order
  # (so pages URL pairings are always consistent)
  names = params[:url_pair].split('-').sort

  # show 404 not found if the names are the same
  raise ActiveRecord::RecordNotFound if names.uniq.count == 1

  # see if they are valid on the database. Note the use of find_by!,
  # so if either one or both don't exist, a RecordNotFound error will be raised,
  # resulting in a 404 not found page
  @activities = names.each { |n| ActivitiesModel.find_by!(name: n) }

  # if you've reached here, then we get to view rendering.
  # @activities is available to map up the view
end

如果你需要创建一个站点地图,或者有一个有效页面的列表 - 这将得到一个包含所有有效配对的数组:

# you could also load these from the DB
# e.g. Model.pluck(:name)
values = ["basketball", "soccer", "baseball", "swimming"]

values.combination(2).to_a.map(&:sort)
# => [["basketball", "soccer"], ["baseball", "basketball"], ["basketball", "swimming"], ["baseball", "soccer"], ["soccer", "swimming"], ["baseball", "swimming"]]
相关问题