Reputation: 2869
I'm using Devise with my Rails 4.2 application and I have custom users controller than I use to navigate to a profile page in the users#show route. The problem is, if I call
@user.username
It returns nothing and the value is nil.
Routes:
devise_for :users
resources :users, :only => [:show]
I also made the following adjustments on the config file via the application_controller:
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_in) { |u| u.permit(:email, :password,:username) }
devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:email, :password, :password_confirmation,:username) }
devise_parameter_sanitizer.for(:account_update) { |u| u.permit(:email, :password, :password_confirmation,:username) }
end
The weird thing is, I've seeded the db with default users and they have access to the method. So that leaves me to believe there's a problem with the form. But sure enough, I've enabled the field so it's not like I'm not passing in values.
devise/registrations/new.html.erb
<div class="field">
<%= f.label :username %><br />
<%= f.text_field :username, autofocus: true %>
</div>
Finally, I pass along the user object via the controller like this:
def show
@user = User.find(params[:id])
@posts = @user.posts.last(5)
end
One last thing, if I inspect the user object, it shows that there's a username method but the value is nil.
I've looked at the examples from Devise but still am not getting what's going on.
Upvotes: 2
Views: 2186
Reputation: 2869
Very simple solution actually. The method needs to be called with a before action like this:
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
It's in the docs here: https://github.com/plataformatec/devise#strong-parameters
Upvotes: 1
Reputation: 11
Did you maybe add attr_accessor in your user model?
This may override your values to be nil.
Upvotes: 0