【问题标题】:Why are the nested resources for Devise authentication not working?为什么 Devise 身份验证的嵌套资源不起作用?
【发布时间】:2014-11-24 12:44:33
【问题描述】:

我的 rails 应用有几个出租车司机,他们有几个出租车,它们之间的关系如下:

class Operator < ActiveRecord::Base
    has_many :cabs
end

我希望添加认证系统,以便为每个操作员创建管理员。我正在使用设计。由于我需要创建路径为:operator/:operator_id/admins/sign_up,所以我生成了Admin模型,为:

rails generate devise Admin

然后我修改了我的路线以获得上述路径:

scope "operators/:operator_id" do 
    devise_for :admins
end

运行 rake 路由表明我正在获取所需的 url。我还修改了模型:

class Admin < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  belongs_to :operator
end

class Operator < ActiveRecord::Base
    has_many :admins
end

我还修改了 devise/sessions/new.html.irb 以包含 operator_id 的隐藏字段:

h2>登录

<%= form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %>
  <div><%= f.label :email %><br />
  <%= f.email_field :email, autofocus: true %></div>

  <div><%= f.label :password %><br />
    <%= f.password_field :password, autocomplete: "off" %></div>

  <% if devise_mapping.rememberable? -%>
    <div><%= f.check_box :remember_me %> <%= f.label :remember_me %></div>
  <% end -%>

  <% f.hidden_field :operator_id, :value => params[:operator_id] %>

  <div><%= f.submit "Log in" %></div>
<% end %>

<%= render "devise/shared/links" %>

最后,为了在访问 cab 详细信息之前对管理员进行身份验证,我在 cabs_controller 中添加了以下内容:

before_filter :authenticate_admin!

问题是我无法提交管理表单。当我提交管理员凭据时,表单没有响应。我哪里错了?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 devise nested-resources


    【解决方案1】:

    您必须将:operator_id 添加到Devise 的允许参数中

    Take a look here

    基本上,您想在application_controller.rb 中关注:

    before_action :configure_permitted_parameters, if: :devise_controller?
    
      protected
    
        def configure_permitted_parameters
          devise_parameter_sanitizer.for(:sign_up) do |u|
            u.permit(:email, :password, :password_confirmation, :operator_id) #add :operator_id
          end
        end
    

    【讨论】:

    • 重新启动服务器....现在似乎可以工作了...但是新管理员没有获得与之关联的 operator_id。
    • 这意味着管理员可以访问另一个出租车运营商的出租车,这是我绝对买不起的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-04
    • 2019-10-31
    • 2019-04-08
    • 1970-01-01
    • 1970-01-01
    • 2016-11-24
    相关资源
    最近更新 更多