【问题标题】:Scoping current accounts in the url在 url 中确定当前帐户的范围
【发布时间】:2014-02-10 15:30:57
【问题描述】:

Basecamp 如何将他们的路线设置为当前帐户的范围?

basecamp.com/12345/

12345 是一个帐号。如何设置路线以达到相同的效果?

我不想将帐号传递给我的所有路线。

new_account_post_comments_path(@account, @post)
# /account/12345/posts/12345

我想这样做:

new_post_comments_path(@post)
# /12345/posts/12345

换句话说,我不想将帐户对象传递给我的所有网址。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 routes


    【解决方案1】:

    我猜测当前的 account_id 可能存储在会话中,并且路由看起来类似于这样:

      scope "/:account_id", account_id: lambda{|request| request.session[:account_id]} do
        resources :posts
      end
    

    【讨论】:

    • 你会如何使用像/foo 这样不属于帐户ID范围的网址?
    • 我不确定我是否理解你的问题。您始终可以在范围块之外定义路由。
    • 是的,但如果我定义类似get '/foo', to 'foos#foo' 的内容,它不会尝试使用account_id = foo 查找帐户。我的意思是,它怎么知道.com/foo 不是.com/:account_id
    • 如果您在范围块之前定义get '/foo', to: 'foos#foo',它将首先匹配。
    • 我认为将当前帐户 ID 存储在会话中以进行范围界定没有任何问题。但是有一个问题:您应该始终确保用户在页面加载时可以访问该帐户。我建议您创建一个辅助方法 current_account 执行以下操作:current_user.accounts.find(session[:account_id])
    猜你喜欢
    • 2011-12-08
    • 1970-01-01
    • 2012-03-03
    • 2012-08-15
    • 2012-01-01
    • 1970-01-01
    • 2011-09-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多