User Model
class User < ApplicationRecord
belongs_to :tenant, dependent: :destroy
end
Tenant Model
class Tenant < ApplicationRecord
has_many :users
end
Controller
Workaround 1 (not working)
def create
super
#tenant = Tenant.new
#user = #tenant.build_user(params)
#tenant.save
end
Workaround 2 (not working)
def create
#tenant = Tenant.new
#user = User.build(params)
#tenant.save
super
end
Is there any possibilities to pass a parameter to devise super class?
Since Devise super method has its own functionality on user registration/password hashing/, I can not completely override the function.
I know the way I am saving is wrong, please suggest me the better approach.
Actual source code:
(with Controller, Model, Migrations and Routes files are added.)
https://repl.it/#aravin/HarmlessRepentantHarddrive
You can override the sign_up_params in your controller:
class RegistrationsController < Devise::RegistrationsController
private
def sign_up_params
params.require(:user).permit(:first_name, :last_name, :email, :password, :password_confirmation...).merge({tenant_id: Tenant.create!.id})
end
end
I wanted to provide a little more verbose answer than was provided by AbM.
You can generate the registrations_controller.rb file with the following command:
rails g devise:controllers users -c=registrations
Once you do this, you will want to modify it such that you have something like:
class RegistrationsController < Devise::RegistrationsController
private
def sign_up_params
params.require(:user).permit(:first_name, :last_name, :email, :password, :password_confirmation)
end
def account_update_params
params.require(:user).permit(:first_name, :last_name, :email, :password, :password_confirmation, :current_password)
end
end
Then in your routes.rb file you will want to change the devise_for line to tell devise that you want to override your registrations controller like:
devise_for :users, controllers: { registrations: 'users/registrations' }
Of course, you will want to replace the :user/:users references to the name of your devise authentication model if you are using something other than the standard User throughout my example.
Here is a reference to this in the official docs on GitHub.
Related
First this is all of my code
#models/user.rb
class User < ApplicationRecord
has_many :trips
has_many :homes, through: :trips
has_secure_password
accepts_nested_attributes_for :trips
accepts_nested_attributes_for :homes
validates :name, presence: true
validates :email, presence: true
validates :email, uniqueness: true
validates :password, presence: true
validates :password, confirmation: { case_sensitive: true }
end
#home.rb
class Home < ApplicationRecord
has_many :trips
has_many :users, through: :trips
validates :address, presence: true
end
class HomesController < ApplicationController
def show
#home = Home.find(params[:id])
end
def new
if params[:user_id]
#user = User.find_by(id: params[:user_id])
#home = #user.homes.build
end
end
def create
#user = User.find_by(id: params[:user_id])
binding.pry
#home = Home.new
end
private
def home_params
params.require(:home).permit(:address, :user_id)
end
end
I am trying to do something like this so that the home created is associated with the user that is creating it.
def create
#user = User.find_by(id: params[:user_id])
#home = Home.new(home_params)
if #home.save
#user.homes << #home
else
render :new
end
end
The problem is that the :user_id is not being passed into the params. So the #user comes out as nil. I can't find the reason why. Does this example make sense? Am I trying to set the associations correctly? Help or any insight would really be appreciated. Thanks in advance.
The way you would typically create resources as the current user is with an authentication such as Devise - not by nesting the resource. Instead you get the current user in the controller through the authentication system and build the resource off it:
resources :homes
class HomesController < ApplicationController
...
# GET /homes/new
def new
#home = current_user.homes.new
end
# POST /homes
def create
#home = current_user.homes.new(home_parameters)
if #home.save
redirect_to #home
else
render :new
end
end
...
end
This sets the user_id on the model (the Trip join model in this case) from the session or something like an access token when dealing with API's.
The reason you don't want to nest the resource when you're creating them as a specific user is that its trivial to pass another users id to create resources as another user. A session cookie is encrypted and thus much harder to tamper with and the same goes for authentication tokens.
by using if params[:user_id] and User.find_by(id: params[:user_id]) you are really just giving yourself potential nil errors and shooting yourself in the foot. If an action requires a user to be logged use a before_action callback to ensure they are authenticated and raise an error and bail (redirect the user to the sign in). Thats how authentication gems like Devise, Knock and Sorcery handle it.
Im using Devise to create my users in an App with Ruby on Rails.
I have a User model that has a Plan (hobby,premium, etc...)
When creating a new user, I want to add the basic plan to this new user (for business rules needs, I cant leave it blank).
The question is, how can I add this plan when creating this new user?
Here is my controller:
class RegistrationsController < Devise::RegistrationsController
clear_respond_to
respond_to :json
def save_user_type
session[:user_type] = params[:user_type]
end
private
def sign_up_params
params.require(:user).permit(:first_name, :last_name, :email, :password, :password_confirmation, :type, :provider )
end
end
In which method should I add something like this?
#user.plan = Plan.first
#user.save
class User < ActiveRecord::Base
has_one :plan
after_create :build_default_plan
private
def build_default_plan
plan.create(#paln_params)
#.. so on
end
end
Added this line to the user model
after_create do |user|
user.plan = Plan.first
user.save
end
I'm using devise_token_authentication gem to build token based authentication rails api, then after that I added some extra fields to Vendor model through different migration, and in order to permit them I wrote this:
class ApplicationController < ActionController::Base
before_action :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [:first_name, :last_name, :tax_number])
devise_parameter_sanitizer.permit(:account_update, keys: [:first_name, :last_name, :tax_number])
end
end
Then after that I added another model Customer rails g devise_token_auth:install Customer auth
then in routes.rb
Rails.application.routes.draw do
mount_devise_token_auth_for 'Vendor', at: 'vendor/auth'
mount_devise_token_auth_for 'Customer', at: 'customer/auth'
end
each time I try to sign_up with customers through 'localhost:3000/customer/auth' I got error message: ActiveModel::UnknownAttributeError: unknown attribute 'tax_number' for Customer.
So is there any way to permit the extra fields only for Vendor model and skip 'Customer' ?
look on this setup for multiple devise user models.
or
If you override the RegistrationsController you need to permit extra params directly in registrationsController
class Users::RegistrationsController < DeviseTokenAuth::RegistrationsController
def create
end
def account_update
end
private
def sign_up_params
params.require(:user).permit(:email, :password, :password_confirmation, :first_name, :last_name, :tax_number)
end
end
First of all, I am fully aware of the bad practice with mixing the two.
I have a model that has attr_accessible set up. I'd like to start transitioning our application to strong_parameters. The problem is that I need to do this piecemeal as we refactor individual parts of the application. Is there a ActiveRecord method I can use to update the attributes that bypasses attr_accessible for right now? Or can I define a attr_accessible=false type of thing that bypasses it?
Code example:
Model:
class User < ActiveRecord::Base
attr_accessible :first_name, :last_name, :email, :password
end
Controller:
class UsersController < ApplicationController
before_action :set_user
def update
#user.assign_attributes(user_params)
#user.save!
end
private
def set_user
#user = User.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def user_params
params.require(:user).permit(
:first_name, :last_name, :email, :other_attribute_not_in_accessible
)
end
end
Found it!
In the controller, do this:
#user.update_attributes(user_params,:without_protection=>true)
And then it'll work.
I am currently using Rails 4 and Devise 3.0.0. I have tried to add a custom field of "Name" to the sign up form and edit registration form. Whenever I submit the form, the following errors arise:
Unpermitted parameters: name
WARNING: Can't mass-assign protected attributes for User: email, password, password_confirmation.
I understand that this has something to do with the way Rails 4 handles parameters, but I do not understand what I am supposed to do about it right now. I have searched around and have seen that I am supposed to add some lines to a User model involving "params."
My user model currently looks like this:
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable, #:recoverable,
:rememberable, :trackable, :validatable
attr_accessible :name, :password, :password_confirmation, :remember_me, :email
end
According to How is attr_accessible used in Rails 4?, I am supposed to add the following code to "The controller."
class PeopleController < ApplicationController
def create
Person.create(person_params)
end
private
def person_params
params.require(:person).permit(:name, :age)
end
end
What controller? And is this literal code? Since I am dealing with User, do I have to use User.create(user_params)? instead of Person.create(person_params)?
Rails 4 has moved parameter sanitisation to the Controller from the Model. Devise handles it for 3 actions, sign_in, sign_up and account_update. For sign_up, the permitted parameters are authentication key (which is :email by default), password and password_confirmation.
If you want to add :name to the User model and use it for sign_up, either change config.authentication_keys = [ :email ] to config.authentication_keys = [ :name ] in /config/initializers/devise.rb or, if you want to use both :email and :name, add this to the ApplicationController
class ApplicationController < ActionController::Base
before_action :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) << :username
end
end
Also check-
https://github.com/plataformatec/devise#strong-parameters
You have to add this in controller where you have written User.create(user_params). I am assuming that UsersController.
class UsersController < ApplicationController
def create
User.create(user_params)
end
private
def user_params
#assumption: user params are coming in params[:user]
params.require(:user).permit(:name, :age, :and_other_params_you_want_to_allow)
end
end
Yes, you should add one line which is like:-
attr_accessible :name
in your model to allow name to assigned and if it does not work try this How is attr_accessible used in Rails 4?
I have similar problem. So, to fix it I created custom registration controller inherit form DeviseRegistration controller. Check Devise documentation and define controller like this.
class RegistrationsController < Devise::RegistrationsController
before_filter :update_sanitized_params, if: :devise_controller?
def update_sanitized_params
devise_parameter_sanitizer.for(:sign_up) {|u| u.permit(:name, :email, :)}
end
end
Make sure you have define this routes for this controller in config/routes.rb
devise_for :users, :controllers => {:registrations => "registrations" } , :path => '', :path_names => {
:sign_in => 'login',
:sign_out => 'logout'
}
Check this documentation of devise for strong parameter.
i had similar issues, this was my fix:
class ApplicationController < ActionController::Base
before_filter :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:account_update) { |u| u.permit!}
end
end