Why are the nested resources for Devise authentication not working?

79 views Asked by At

My rails app has a few cab operators and they have a few cabs, and they are related as follows:

class Operator < ActiveRecord::Base
    has_many :cabs
end

I wish to add authentication system so as to create admins for each operator. I am using Devise. Since I need to create path as: operator/:operator_id/admins/sign_up, I generated the Admin model, as:

rails generate devise Admin

Then I modified my routes so as to obtain the above mentioned path:

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

Running rake routes shows that I am getting the required urls. I also modified the models:

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

  belongs_to :operator
end

class Operator < ActiveRecord::Base
    has_many :admins
end

I also modified the devise/sessions/new.html.irb to include a hidden field for operator_id:

h2>Log in

<%= 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" %>

Finally, in order to authenticate admins before accessing the cab details, I added the following to the cabs_controller:

before_filter :authenticate_admin!

The problem is I am unable to submit the admin form. The form doesn't respond when I submit the admin credentials. Where am I going wrong?

1

There are 1 answers

2
Andrey Deineko On BEST ANSWER

You have to add :operator_id to Devise's permitted parameters

Take a look here

Essentially, you want to go with following in 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