ActiveModel::ForbiddenAttributesError in Devise::RegistrationsController#create - ruby-on-rails-4

I am getting this
ActiveModel::ForbiddenAttributesError in Devise::RegistrationsController#create
error when i used devise gem
error in console is
Parameters: {"utf8"=>"✓", "authenticity_token"=>"kwJU2b47XvXj9hNV1HAdttW/rvetDepAVCn+jPvndy8=", "user"=>{"email"=>"nagarajureddy#gmail.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Sign up"}
Completed 500 Internal Server Error in 1ms
ActiveModel::ForbiddenAttributesError (ActiveModel::ForbiddenAttributesError): activemodel (4.1.0) lib/active_model/forbidden_attributes_protection.rb:21:in `sanitize_for_mass_assignment'
Please any one help me

Add this in your application controller and restart the server, It's because of Strong Parameters in Rails4.
before_filter :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:email, :password, password_confirmation) }
devise_parameter_sanitizer.for(:account_update) { |u| u.permit(:email, :password, password_confirmation) }
end

Related

NoMethodError name RoR user.name

Followed the tutorial at SitePoint
for a simple sorcery app. I am receiving undefined method `name' for nil:NilClass
migration
class SorceryCore < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name
t.string :email, :null => false
t.string :crypted_password
t.string :salt
t.timestamps :null => false
end
add_index :users, :email, unique: true
end
end
/home/david/Magical/app/views/user_mailer/activation_needed_email.html.erb
<p>Welcome, <%= #user.name %>!</p>
<p>To login to the site, just follow <%= link_to 'this link',
activate_user_url$
<p>Thanks for joining and have a great day!</p>
users.rb
class User < ActiveRecord::Base
authenticates_with_sorcery!
validates :password, length: { minimum: 3 }
validates :password, confirmation: true
validates :email, uniqueness: true, email_format: { message: 'has
invalid format'
End
I took the long way home and cloned the Github repo. At first I was getting a 'stack level too deep' error, but I found that the gemfile loaded rails 4.2.1 .
I changed this to 4.2.10 and all went well after the migrations and minor tweaks in the tutorial.
along the way, I found rails_db gem which is a great simple gem for working with sqLite. rails_db gem

Devise validation fails with can't be blank even if I send values properly

I am sending the request using postman, all the required fields are in place, however, I get the params required errors, like I send nothing when I actually do send the required params to the server.
I was reading this blog that says in order to get json reponse in devise I just need to add respond_to :json line in devise controllers, but it seems this is not enough.
I would've add more info to the question if I would know what exactly is needed.
routes:
namespace :api, defaults: { format: :json } do
devise_for :users, controllers: {
registrations: 'api/users/registrations',
sessions: 'api/users/sessions',
invitations: 'api/users/invitations'
}
end
controllers:
module Api
class Users::RegistrationsController < Devise::RegistrationsController
respond_to :json
layout false, only: :create
def create
build_resource(sign_up_params)
resource.save
yield resource if block_given?
if resource.persisted?
# valid resource
else
clean_up_passwords resource
set_minimum_password_length
render json: {user: resource.errors}
end
end
end
end
class ApplicationController < ActionController::Base
protect_from_forgery with: :null_session
before_action :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) << [:first_name, :last_name]
end
end
request:
with headers: Accept - application/json
Started POST "/api/users" for 127.0.0.1 at 2015-07-01 17:05:26 +0300
Processing by Api::Users::RegistrationsController#create as JSON
Parameters: {"user"=>{"email"=>"usermail#gmail.com", "password"=>"[FILTERED]", "first_name"=>"firstName", "last_name"=>"lastName"}}
(0.1ms) BEGIN
(0.1ms) ROLLBACK
Completed 200 OK in 17ms (Views: 0.2ms | ActiveRecord: 3.8ms)
response:
{"user":{"email":["can't be blank"],"password":["can't be blank"],"first_name":["can't be blank"],"last_name":["can't be blank"]}}

Strong parameters with Rails 4.0 and Devise

I am using Rails 4.2 and devise.Request type will always be JSON.My registrations controller looks like this
class Users::RegistrationsController < Devise::RegistrationsController
before_filter :configure_sign_up_params, only: [:create]
def create
if request.format(request) == "application/json"
build_resource(sign_up_params)
if resource.save
render :json => {:success => "true", :message => "Thank You For Registering."}
else
render :json => {:success => "false", :message => resource.errors.full_messages}
end
else
super
end
end
protected
def configure_sign_up_params
devise_parameter_sanitizer.for(:sign_up) do |u|
u.permit(:email, :password, :password_confirmation)
end
end
end
The parameters that show-up in the console is like :
Parameters: {"email"=>"test123#gmail.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "registration"=>{"email"=>"test123#gmail.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}}
The error it produces is that the controller doesn't recognize the email and password fields and always returns error like :
["Email can't be blank","Password can't be blank"]
Does this happen because of any foolishness that I have written in the code?Please help
Your configure_sign_up_params method has to be something like this to work.
def configure_sign_up_params
devise_parameter_sanitizer.for(:registration) do |u|
u.permit(:email, :password, :password_confirmation)
end
end
If you can see the console content what you have posted, it contains a hash with registration as a key:
"registration"=>{"email"=>"test123#gmail.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}

devise current_user found in a session controller, but it became nil when comes to another controller

I am using devise for authentication,
I put some text after "super" in SessionsController#create method like below, to find the "current_user" value in the browser(using better_errors gem).
class SessionsController < Devise::SessionsController
def new
super
end
def create
super
error_debug
end
def edit
super
end
end
in routes.rb
root :to => "welcome#index"
I got the current_user value like expected in SessionsController#create, but current user value is 'nil' when it comes to welcome#index method even after signin.
I can't able to find the reason behind it, please someone assist me to resolve this issue.
First signed in and check in better_error value of current_user
I checked the log file, I found that, the bug is
Dall::error server not found
Then I installed memcached by doing sudo apt-get install memcached. It works fine now. For more clarification, click the below link
Rails + Dalli memcache gem: DalliError: No server available
Follow the below steps:
gem install 'devise'
rails generate devise:install
rails generate devise User
rake db:migrate
Your Routes should be like this
devise_for :users
>
root :to => "home#index"
Change your development config add following line to config/environments/development.rb
config.action_mailer.default_url_options = { host: 'localhost:3000' }
Add this code to your controller
before_filter :authenticate_user!
And if you are using rails 4 so add this code to your application
class ApplicationController < ActionController::Base
before_filter :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) { |u| u.permit({ roles: [] }, :email, :password, :password_confirmation) }
devise_parameter_sanitizer.for(:sign_in) { |u| u.permit(:username, :email) }
end
end
Do you have protect_from_forgery method call in your application controller? Look at this guides.rubyonrails.org/security.html

Mongoid Model won't persist has_one via embeds_one relation

I'm having trouble with embeds in a mongoid4-based rails 4 app. I've been looking for an answer everywhere for the past 2 days. So here is the code.
This is a church management app, with a Service model, embedding a team and a band. Each team/band has several roles such as "presidence", "communion" that refer to a user.
My models :
class Service
include Mongoid::Document
...
embeds_one :team, autobuild: true
embeds_one :band, autobuild: true
...
accepts_nested_attributes_for :team, :band
end
class Team
include Mongoid::Document
embedded_in :service
has_one :presidence, :class_name => 'User', autosave: true
has_one :message, :class_name => 'User', autosave: true
...
end
class Band
include Mongoid::Document
has_one :lead, :class_name => 'User', autosave: true
has_one :guitar, :class_name => 'User', autosave: true
...
embedded_in :service
end
class User
include Mongoid::Document
embeds_one :profile
belongs_to :team, :inverse_of => :presidence
belongs_to :team, :inverse_of => :message
belongs_to :band, :inverse_of => :lead
belongs_to :band, :inverse_of => :guitar
def fullname
"#{profile.firstname} #{profile.lastname}"
end
def self.find_by_talent(talent)
self.where("profile.talents.name" => talent)
end
end
The services controller :
# POST /services
# POST /services.json
def create
#service = Service.new(service_params)
respond_to do |format|
if #service.save
format.html { redirect_to #service, notice: 'Service was successfully created.' }
format.json { render action: 'show', status: :created, location: #service }
else
format.html { render action: 'new' }
format.json { render json: #service.errors, status: :unprocessable_entity }
end
end
end
...
def service_params
params.require(:service).permit(:date, :time, :place, :name, :theme, :team => [:id, :precedence, :message ], :band => [:id, :lead, :guitar ])
end
And the form in _form.html.erb :
<%= form_for(#service) do |f| %>
...
<%= f.fields_for #service.team do |tf| %>
<%= tf.collection_select :presidence, User.find_by_talent(:presidence), :_id, :fullname, {:include_blank => "select a person"} %>
<%= tf.collection_select :message, User.find_by_talent(:message), :id, :fullname, {:include_blank => "select a person"} %>
<% end %>
<%= f.fields_for #service.band do |bf| %>
<%= bf.collection_select :lead, User.find_by_talent(:lead), :id, :fullname, {:include_blank => "select a person"} %>
<%= bf.collection_select :guitar, User.find_by_talent(:guitar), :id, :fullname, {:include_blank => "select a person"} %>
<% end %>
...
<% end %>
When creating a service, everything seems to run fine, but this is what I get in the console :
2.0.0-p195 :001 > s = Service.last
=> #<Service _id: 52ea18834d61631e7e020000, date: "2014-02-02", time: "10:00", place: "Where it's at", name: "My great name", theme: "The service's theme">
2.0.0-p195 :002 > s.team
=> #<Team _id: 52ea18834d61631e7e030000, >
2.0.0-p195 :003 > s.team.presidence
=> nil
Why is s.team.presidence not created ? s.team looks weird, too, with an ending comma...
Here is the content of my rails log :
Started POST "/services" for 127.0.0.1 at 2014-01-30 10:16:51 +0100
Processing by ServicesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Ph6lbdHC2FbiANn/fGSzHWprenj3fWKXM40Hrsc5+AM=", "service"=>{"date"=>"2014-02-02", "name"=>"My great name", "theme"=>"The service's theme", "time"=>"10:00", "place"=>"Where it's at", "team"=>{"presidence"=>"52ea18324d61631e81010000", "message"=>"52ea18324d61631e81010000"}, "band"=>{"lead"=>"52ea18324d61631e81010000", "guitar"=>"52ea18324d61631e81010000"}}, "commit"=>"Create Service"}
MOPED: 127.0.0.1:27017 COMMAND database=admin command={:ismaster=>1} runtime: 0.6610ms
MOPED: 127.0.0.1:27017 UPDATE database=service_boot_camp_development collection=users selector={"band_id"=>BSON::ObjectId('52ea18834d61631e7e010000'), "_id"=>{"$nin"=>[]}} update={"$set"=>{"band_id"=>nil}} flags=[:multi]
COMMAND database=service_boot_camp_development command={:getlasterror=>1, :w=>1} runtime: 0.5800ms
MOPED: 127.0.0.1:27017 INSERT database=service_boot_camp_development collection=services documents=[{"_id"=>BSON::ObjectId('52ea18834d61631e7e020000'), "date"=>"2014-02-02", "time"=>"10:00", "place"=>"Where it's at", "name"=>"My great name", "theme"=>"The service's theme", "team"=>{"_id"=>BSON::ObjectId('52ea18834d61631e7e030000')}, "band"=>{"_id"=>BSON::ObjectId('52ea18834d61631e7e010000')}}] flags=[]
COMMAND database=service_boot_camp_development command={:getlasterror=>1, :w=>1} runtime: 2.7460ms
I guess I'm doing something wrong, but I have no clue if it is in the database model or in the form... or anything else...
You will not be able to do it this way. When you create an embedded document, its _id and all of its data are embedded directly within the parent document. This is in contrast to an association, where the document with the belongs_to gets a foreign key which points to its associated parent document. So here, your User documents each have a team_id and band_id, but when the database tries to get the documents, it can't find them, since you can't query directly for embedded documents; you need the parent document first. For more, see the Mongoid documentation.
Another potential issue is that you have multiple belongs_to definitions in the User models. This will also cause an issue, because for each one of those, Mongoid will attempt to create a team_id and band_id. You should name them separately and specify a class name; perhaps names like :presiding_team and :message_team, :lead_band and :guitar_band, etc. This answer should show you what that would look like.
I would recommend making the Team and Band separate referenced documents instead of embedded documents, since you won't be able to reference users effectively while they're embedded.
Hope this helps.