2016-11-11 64 views
0

我有模型用戶包含列角色。如何用角色替換用戶模型的路由

class CreateUsers < ActiveRecord::Migration[5.0] 
    def change 
    create_table :users do |t| 
     t.string :name 
     t.string :email 
     t.string :address 
     t.integer :role 
     t.timestamps 
    end 
    end 
end 

作用店如果User.role = 1,作用是託運人User.role = 0

的routes.rb

resources :users 

和URL的行動顯示(配置文件):http://localhost:3000/users/1

我想改變它:角色。例如: http://localhost:3000/shops/1(如果User.role = 1) 或.../shippers/1(如果User.role = 0)。

我不知道該怎麼做。幫幫我,謝謝!

+1

[Rails Routes based on condition]的可能重複(http://stackoverflow.com/questions/11230130/rails-routes-based-on-condition) – Pavan

+0

http://bjedrocha.com/rails/2015/03/18/role-based-routing-in-rails /請嘗試這個我認爲這可以幫助你 –

回答

0

如果你只是想映射這條路線,你可以做

match '/shops/1', to: 'users#show' 
match '/shippers/1', to: 'users#show' 

這樣,你正在處理與用戶結構下的顯示控制器,這條路線。然後,/shops/1的html應該仍然在views/users/show之下,因爲rails會查找與控制器同名的視圖來呈現頁面。

[更新]

然後,在你的控制器,你可以說

<% if User.role == 1 %> 
    <%redirect_to show_user_path%> 
+0

看到我上面更新的評論^^^ –

1

首先,你最好在你的模型中使用的enum。通過這種方式,您可以分配的實際作用到User.role屬性(不僅僅是整數):

#app/models/user.rb 
class User < ActiveRecord::Base 
    enum role: [:shipper, :shop] 
end 

這仍然將保持在數據庫中integer,但分配實際名稱中的ActiveRecord的作用。例如,您將獲得user.shipper?user.shop?


因爲我很感興趣,看到一個決定,我上網看了一下,發現this

它解釋了我的想法 - 您需要使用約束來驗證用戶的角色並進行相應的重定向。這樣,您可以使用單個路由幫助程序,並根據用戶的角色將用戶發送到不同的路由。

this answer,我想嘗試這樣的:

# lib/role_constraint.rb 
class RoleConstraint 
    def initialize(*roles) 
    @roles = roles 
    @role = request.env['warden'].user.try(:role) 
    end 

    def matches?(request) 
    params = request.path_parameters 
    @roles.include?(@role) && @role == params[:role] 
    end 
end 


#config/routes.rb 
resources :users, path: "", except: :show do 
    get ":role/:id", action: :show, on: :collection, constraints: RoleConstraint.new([:shipper, :shop]) 
end 

這不正是我想要的,但它應該建立一個單一的路線,這是隻有一個角色的用戶訪問作爲託運人或商店。

+0

它顯示:「未初始化的常量RoleConstraint」? –

+0

您需要將lib目錄添加到自動加載路徑中http://stackoverflow.com/a/19650564/1143732 –