【问题标题】:rails 5 dynamic routing redirections based on model attributesrails 5 基于模型属性的动态路由重定向
【发布时间】:2018-11-01 05:06:46
【问题描述】:

我有以下资源

Places (:place_id, :name, :shortlink, :token)

Events (:event_id, :address)

我有一个嵌套用户资源的受限用户注册(用户有很多事件)。

当用户注册时,他(s)创建一个带有引用地点列的新事件。

用户只有在 url 中有这些参数时才能注册

https://mysite/user/signup?q=[:place_id]&t=[:token]#place id必须存在,place token必须等于t参数

before_action :check_has_access, only: [:new]
...
protected

def check_has_access
  @place = Place.find(params[:q])
   if params[:q].blank? && @place.blank? || params[:t].blank? || @place.token != params[:t]
     redirect_to(root_path)
     flash[:alert] = 'Restricted sign-up'
   end
end

我想为每个地方生成一个快捷方式供用户注册

https://mysite/[:shortlink]#place.shortlink

这将重定向到具有相应填写的表单和受限参数的给定注册表单,以便拥有直接 url 的用户可以注册。

https://mysite/user/signup?q=[:place_id]&t=[:token]

如何生成路线?

辅助问题,我做得对吗?

【问题讨论】:

    标签: ruby-on-rails routes


    【解决方案1】:

    在这篇帖子here找到了解决方案。

    我需要重新启动服务器,以便在创建 Place 对象后加载新创建的路由。不确定我是否做得对,但它确实有效..

    #config/route.rb
    
     Rails.application.routes.draw do
        Place.all.each do |pl|
             get "/#{pl.shortlink}" => redirect("/users/sign_up?q=#{pl.id}&t=#{pl.token}")
           end
        end
    

    为了load添加地点时新创建的路线,我添加了

    #models/place.rb
    
    after_create :add_shortlink
    ...
      def add_shortlink
      Rails.application.reload_routes!
    end
    

    这不适用于 Heroku,解决的问题是 here

    【讨论】:

      猜你喜欢
      • 2016-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多