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?
You have to add
:operator_id
to Devise's permitted parametersTake a look here
Essentially, you want to go with following in
application_controller.rb
: