Rails 4: nested attributes not displaying with Devise - ruby-on-rails

I am trying to include nested attributes inside my Devise edit.html.erb file.
My models:
class User < ActiveRecord::Base
has_one :tutor, dependent: :destroy
accepts_nested_attributes_for :tutor, allow_destroy: true
devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable
end
and
class Tutor < ActiveRecord::Base
belongs_to :user
end
in my ApplicationController:
class ApplicationController < ActionController::Base
before_filter :configure_permitted_parameters, if: :devise_controller?
protect_from_forgery with: :exception
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:account_update) do |u|
u.permit(:first_name, :last_name, :email,
:is_tutor, :password,
# This is important for nested attributes
tutor_attributes: [:id, :_destroy, :user_id, :description]
:password_confirmation, :current_password)
end
end
end
And my view:
<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name), :html => { :multipart => true }) do |f| %>
<%= devise_error_messages! %>
<div><%= f.label :email %><br />
<%= f.email_field :email, :autofocus => true %></div>
<% if devise_mapping.confirmable? && resource.pending_reconfirmation? %>
<div>Currently waiting confirmation for: <%= resource.unconfirmed_email %></div>
<% end %>
<div><%= f.label :first_name %><br />
<%= f.text_field :first_name %></div>
<div><%= f.label :last_name %><br />
<%= f.text_field :last_name %></div>
<p>
<%= f.check_box :is_tutor %>
<%= f.label :is_tutor, 'Tutor' %>
</p>
<div>
<%= f.fields_for :tutor do |builder| %>
<fieldset>
<%= builder.label :description, 'Description' %><br />
<%= builder.text_area :description %><br />
<%= builder.check_box :_destroy %>
<%= builder.check_box :_destroy, 'Remove description' %>
</fieldset>
<% end %>
</div>
<br />
<div><%= f.label :password %> <i>(leave blank if you don't want to change it)</i><br />
<%= f.password_field :password, :autocomplete => "off" %></div>
<div><%= f.label :password_confirmation %><br />
<%= f.password_field :password_confirmation %></div>
<div><%= f.label :current_password %> <i>(we need your current password to confirm your changes)</i><br />
<%= f.password_field :current_password %></div>
<div><%= f.submit "Update" %></div>
<% end %>
When I go to the edit page, I do not see the fieldset with the nested attributes. The query to the db looks like this:
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 ORDER BY "users"."id" A
SC LIMIT 1
Tutor Load (3.2ms) SELECT "tutors".* FROM "tutors" WHERE "tutors"."user_id" = ? ORDER BY "tuto
rs"."id" ASC LIMIT 1 [["user_id", 1]]
Any idea what I might be doing wrong?
Thanks!

This is probably due to the fact there is not a tutor association connected to the user. The fields would not show if the tutor was nil.
If so, you'll need to figure out how to do this on the user.
#user.build_tutor
Some options for adding this - You may need to overwrite the devise controller/method to add this. There may be some hooks provided by devise. You may do this in the view.

Related

Nested Form for Join Table

I'm attempting to add a nested form into the Devise registration form.
My 3 tables are Users (devise), Languages, and they both are joined in Languages_Users
It signs up the new user, but does not save Languages_Users, but I see that it is passed in the params. A new issue has also arisen - the avatar file is no longer saved. I'm not sure if these are related (if not, don't worry about addressing it).
**UPDATE - Here are my current logs - I now think the issue due to languages_users not receiving user_id
"languages users can't be blank'. In my logs though, it says 'SELECT 1 AS one FROM "languages_users" WHERE ("languages_users"."user_id" IS NULL AND "languages_users"."language_id" = 2) LIMIT 1' Is this an issue with not passing the user_id?
**
User.rb
class User < ActiveRecord::Base
has_many :languages_users
has_many :languages, :through => :languages_users
accepts_nested_attributes_for :languages_users
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
belongs_to :role
has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "100x100#" }, :default_url => "/images/:style/missing.png"
validates_attachment_content_type :avatar, :content_type => /\Aimage\/.*\Z/
validates_presence_of :first_name, :last_name, :location, :nationality, :bio
end
registrations_controller.rb
class Users::RegistrationsController < Devise::RegistrationsController
before_filter :configure_permitted_parameters
def new
build_resource({})
resource.languages_users.build
respond_with self.resource
end
def create
super
end
private
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) { |u|
u.permit(:email, :password, :password_confirmation, :bio, :location, :last_name, :first_name, :nationality, :avatar, languages_user_attributes: [:id, :language_id, :user_id, :level]) }
end
end
in registrations:
new.html.erb
<h2>Sign up</h2>
<%= form_for(resource, as: resource, url: registration_path(resource)) do |f| %>
<%= devise_error_messages! %>
<div class="field">
<%= f.label :first_name %><br />
<%= f.text_field :first_name, autofocus: true %>
</div>
<div class="field">
<%= f.label :last_name %><br />
<%= f.text_field :last_name %>
</div>
<div class="field">
<%= f.label :location %><br />
<%= f.text_field :location %>
</div>
<div class="field">
<%= f.label :nationality %><br/>
<%= f.text_field :nationality %>
</div>
<div class="field">
<%= f.label :bio %><br />
<%= f.text_field :bio %>
</div>
<div class="field">
<%= f.label :email %><br />
<%= f.text_field :email %>
</div>
<div class="form-group">
<%= f.label :avatar, class: 'col-sm-2 control-label' %>
<div class="col-sm-6">
<%= f.file_field "user[avatar]" %>
</div>
</div>
<%= f.fields_for :langauges_user do |lu| %>
<br>
<div class="fields">
<%= lu.collection_select(:language_id, Language.order('language ASC').all, :id, :language) %><br>
<%= lu.hidden_field :level, value: 1 %>
<% end %>
</div>
<br>
<div class="field">
<%= f.label :password %>
<% if #minimum_password_length %>
<em>(<%= #minimum_password_length %> characters minimum)</em>
<% end %><br />
<%= f.password_field :password, autocomplete: "off" %>
</div>
<div class="field">
<%= f.label :password_confirmation %><br />
<%= f.password_field :password_confirmation, autocomplete: "off" %>
</div>
<div class="actions">
<%= f.submit "Sign up" %>
</div>
<% end %>
logs:
Started POST "/users" for ::1 at 2016-03-26 13:30:40 -0400
Processing by Users::RegistrationsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"x1F0kXqKN2/uu7S6BLxyBgSatcVWiSOLASEYYJ7ZF0b3d8V8O+FVQAO0yhjTJ2LImI+Xy4j7Rn+SvlYjV07mrA==", "user"=>{"first_name"=>"John", "last_name"=>"Smith", "location"=>"NYC", "nationality"=>"American", "bio"=>"hello", "email"=>"johns#gmail.com", "user"=>{"avatar"=>#<ActionDispatch::Http::UploadedFile:0x007f940b16a4f8 #tempfile=#<Tempfile:/var/folders/cn/l75pvjk9707bj93z_yykb0t40000gn/T/RackMultipart20160326-11607-1fg5ncg.JPG>, #original_filename="IMG_4573.JPG", #content_type="image/jpeg", #headers="Content-Disposition: form-data; name=\"user[user[avatar]]\"; filename=\"IMG_4573.JPG\"\r\nContent-Type: image/jpeg\r\n">}, "langauges_users"=>{"language_id"=>"16", "level"=>"1"}, "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Sign up"}
Unpermitted parameters: user, langauges_users
Still a newb, so please let me know if you'd like me to provide anything further.
Thanks!
You should change languages_user to languages_users
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) { |u|
u.permit(:email, :password, :password_confirmation, :bio, :location, :last_name, :first_name, :nationality, :avatar, languages_users_attributes: [:id, :language_id, :user_id, :level]) }
end
Also in fields_for
<%= f.fields_for :languages_users do |lu| %>

Ruby on rails: can't save profile model associated with Devise user

I have Devise user model and associated profile model. Here it is:
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_one :profile, autosave: true
accepts_nested_attributes_for :profile
before_create :build_profile
end
Profile model:
class Profile < ActiveRecord::Base
belongs_to :user
end
Next, I include profile fields in default Devise view:
<h2>Edit <%= resource_name.to_s.humanize %></h2>
<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %>
<%= devise_error_messages! %>
<div class="field">
<%= f.label :email %><br />
<%= f.email_field :email, autofocus: true %>
</div>
<% if devise_mapping.confirmable? && resource.pending_reconfirmation? %>
<div>Currently waiting confirmation for: <%= resource.unconfirmed_email %></div>
<% end %>
<%= f.fields_for :profile do |profile_form| %>
<div class="field">
<%= profile_form.label :username %><br />
<%= profile_form.text_field :username %>
</div>
<div class="field">
<%= profile_form.label :address %><br />
<%= profile_form.text_field :address %>
</div>
<div class="field">
<%= profile_form.label :pin %><br />
<%= profile_form.text_field :pin %>
</div>
<% end %>
<div class="field">
<%= f.label :password %> <i>(leave blank if you don't want to change it)</i><br />
<%= f.password_field :password, autocomplete: "off" %>
</div>
<div class="field">
<%= f.label :password_confirmation %><br />
<%= f.password_field :password_confirmation, autocomplete: "off" %>
</div>
<div class="field">
<%= f.label :current_password %> <i>(we need your current password to confirm your changes)</i><br />
<%= f.password_field :current_password, autocomplete: "off" %>
</div>
<div class="actions">
<%= f.submit "Update" %>
</div>
<% end %>
<h3>Cancel my account</h3>
<p>Unhappy? <%= button_to "Cancel my account", registration_path(resource_name), data: { confirm: "Are you sure?" }, method: :delete %></p>
<%= link_to "Back", :back %>
Now, when I update form, Devise field is updated, but profile fields - not. If I trying to update profile thru rails console, everything works just great.
u = User.find_by(id: 2)
u.profile.pin = 123
u.save
Solved! Just override Devise permitted_parameters in ApplicationController like this:
before_action :configure_devise_permitted_parameters, if: :devise_controller?
protected
def configure_devise_permitted_parameters
registration_params = [:email, :password, :password_confirmation, profile_attributes: [:username, :address, :pin]]
if params[:action] == 'update'
devise_parameter_sanitizer.for(:account_update) {
|u| u.permit(registration_params << :current_password)
}
elsif params[:action] == 'create'
devise_parameter_sanitizer.for(:sign_up) {
|u| u.permit(registration_params)
}
end
end
Thanks #max for answer.

Avatar (picture) can't be blank after avatar attached and form submitted - carrierwave error

I am a newbie in Rails. I use Rails 4.2 with Ruby 2.0, I've installed the carrierwave gem. I followed the instructions how to setup with devise.
But the validation or the picture does not work correctly, cause I always get the "Avatar can't be blank" error message when I attached a picture and submit the form. I have no idea where is my mistake.
User model:
class User < ActiveRecord::Base
mount_uploader :avatar, AvatarUploader
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable,
:omniauthable, :omniauth_providers => [:facebook, :google_oauth2]
after_initialize :set_default_role, :if => :new_record?
# Validations
validates_presence_of :avatar
validates_integrity_of :avatar
validates_processing_of :avatar
def self.from_omniauth(auth)
where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
user.name = auth.info.nickname
user.email = auth.info.email
user.password = Devise.friendly_token[0,20]
end
end
end
Sign up form
<h2>Sign up</h2>
<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { multipart: true }) do |f| %>
<%= devise_error_messages! %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name, autofocus: true %>
</div>
<div class="field">
<%= f.label 'Woman' %><br />
<%= f.radio_button :gender, 'Woman' %>
<br>
<%= f.label 'Man' %><br />
<%= f.radio_button :gender, 'Man' %>
</div>
<div class="field">
<%= f.label :email %><br />
<%= f.email_field :email %>
</div>
<div class="field">
<%= f.label :phone %><br />
<%= f.text_field :phone %>
</div>
<div class="field">
<%= f.label :password %>
<% if #minimum_password_length %>
<em>(<%= #minimum_password_length %> characters minimum)</em>
<% end %><br />
<%= f.password_field :password, autocomplete: "off" %>
</div>
<div class="field">
<%= f.label :password_confirmation %><br />
<%= f.password_field :password_confirmation, autocomplete: "off" %>
</div>
<div class="field">
<%= f.label :city %><br />
<%= f.text_field :city %>
</div>
<div class="field">
<%= f.label :county %><br />
<%= f.text_field :county %>
</div>
<div class="field">
<label>My Avatar</label>
<%= f.file_field :avatar %>
<%= f.hidden_field :avatar_cache %>
</div>
<div class="actions">
<%= f.submit "Sign up" %>
</div>
<% end %>
<%= render "users/shared/links" %>
Application controller's strong parameters:
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_in) { |u| u.permit(:email) }
devise_parameter_sanitizer.for(:sign_up) { |u| u.permit({ roles: [] }, :name, :email, :password, :password_confirmation, :avatar, :avatar_cache) }
devise_parameter_sanitizer.for(:account_update) { |u| u.permit({ roles: [] }, :name, :email, :password, :password_confirmation, :avatar, :avatar_cache) }
end
I really do not see where is my mistake. Maybe do you see?
Because you have this validation:
validates_presence_of :avatar
means, you have to upload an avatar.
You will get this error message: Avatar can't be blank if you try to submit the form without attaching the avatar.
So, make sure you attach an avatar before hitting the Sign Up button.

Rails 4 form_for select tag wont persist when trying to update

So i am trying to implement a dropdown menu in my edit form for users, i used devise, so this edit form is inside my devise/registrations/edit.html.erb file.
first i get and error for undefined method for :optionselect (which seems understandable since i couldn't find this elsewhere other than this select in form_for rails
so this is wrong.
<div class="field">
<%= f.label :role %><br />
<%= f.select :optionselect, User.options %>
</div>
i also had it like this
<div class="field">
<%= f.label :role %><br />
<%= f.select :role, [['Member', 'member'], ['Astronaut', 'astronaut'], ['Candidate', 'candidate']] %>
but no luck. because it wouldn't persist the changes i made when editing the role of the user.
Also the name doesn't persist when trying to update it. maybe that gives us a lead.
models/user.rb
class User < ActiveRecord::Base
has_many :books
has_many :reviews
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable,
:registerable,
:recoverable,
:rememberable,
:trackable,
:validatable
validates :email, presence: true, uniqueness: true
validates_format_of :email, :with => /\A([^#\s]+)#((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create
validates :password,
:presence => { :on => :create },
:length => { :minimum => 6, :allow_nil => true }
OPTIONS = [
{:role => 'memeber'},
{:role => 'astronaut'},
{:role => 'candidate'}
]
def self.options
OPTIONS.map { |option| option[:role] }
end
end
controllers/users_controller.rb
class UsersController < ApplicationController
def index
binding.pry
#users = User.all
end
def show
#user = User.find(params[:id])
end
def update
#user = User.find(params[:id])
if #user.update!(user_params)
redirect_to :action => 'show', :id => #user
else
render :action => 'edit'
end
end
private
def user_params
params.require(:user).permit(:name, :email, :role)
end
end
devise/registration/edit.html.erb
<h2>Edit <%= resource_name.to_s.humanize %></h2>
<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %>
<%= devise_error_messages! %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name, autofocus: true %>
</div>
<div class="field">
<%= f.label :role %><br />
<%= f.select :optionselect, User.options %>
</div>
<div class="field">
<%= f.label :email %><br />
<%= f.email_field :email, autofocus: true %>
</div>
<% if devise_mapping.confirmable? && resource.pending_reconfirmation? %>
<div>Currently waiting confirmation for: <%= resource.unconfirmed_email %></div>
<% end %>
<div class="field">
<%= f.label :password %> <i>(leave blank if you don't want to change it)</i><br />
<%= f.password_field :password, autocomplete: "off" %>
</div>
<div class="field">
<%= f.label :password_confirmation %><br />
<%= f.password_field :password_confirmation, autocomplete: "off" %>
</div>
<div class="field">
<%= f.label :current_password %> <i>(we need your current password to confirm your changes)</i><br />
<%= f.password_field :current_password, autocomplete: "off" %>
</div>
<div class="actions">
<%= f.submit "Update" %>
</div>
<% end %>
<h3>Cancel my account</h3>
<p>Unhappy? <%= button_to "Cancel my account", registration_path(resource_name), data: { confirm: "Are you sure?" }, method: :delete %></p>
<%= link_to "Back", :back %>
Let me know if you need more information
edit.html.erb
<%= f.select(:role, User::USER_OPTIONS) %>
models/user.rb
USER_OPTIONS = ["memeber", "astronaut", "candidate"]

rails devise: user and account system

I've been trying to add an account to a user for a couple of days now.
I've installed Devise with no problems, but now I wanted to add a Company Name field to my registration form.
Here's my code:
app/models/account.rb
class Account < ActiveRecord::Base
attr_accessible :name
has_many :users
accepts_nested_attributes_for :users
end
app/models/user.rb
class User < ActiveRecord::Base
belongs_to :account
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :confirmable
attr_accessible :first_name, :last_name, :account_attributes, :account, :email, :password, :password_confirmation, :remember_me
end
app/views/devise/registrations/new.html.erb
<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>
<%= devise_error_messages! %>
<div><%= f.label :first_name %><br />
<%= f.text_field :first_name %></div>
<div><%= f.label :last_name %><br />
<%= f.text_field :last_name %></div>
<%= f.fields_for :account do |account_form| %>
<div><%= account_form.label :name %><br />
<%= account_form.text_field :name %></div>
<% end %>
<div><%= f.label :email %><br />
<%= f.email_field :email %></div>
<div><%= f.label :password %><br />
<%= f.password_field :password %></div>
<div><%= f.label :password_confirmation %><br />
<%= f.password_field :password_confirmation %></div>
<div><%= f.submit "Sign up" %></div>
<% end %>
This is all the code I have. I haven't changed anything more.
And this is the error I got:
Account(#2175324980) expected, got ActiveSupport::HashWithIndifferentAccess(#2169631580)
Thanks in advance.
EDIT
I've found the solution:
I've changed
<%= f.fields_for :account do |account_form| %>
To
<%= f.fields_for :account_attributes, resource.account do |account_form| %>
Now I'm trying to add a :plan to account_form and I'm getting:
Can't mass-assign protected attributes: plan
EDIT 2
Ok, rookie mistake. I've just added :plan to account model.
After that I was getting an query error, I just changed some fields in my DB from null => false to null => true and voila.
I would expect it to look something like this. This involves subclassing devise's registrations controller
#models
class Account < ActiveRecord::Base
attr_accessible :name
has_many :users
end
class User < ActiveRecord::Base
belongs_to :account
accepts_nested_attributes_for :account
attr_accessible :first_name, :last_name, :account_attributes, :account, :email, :password, :password_confirmation, :remember_me
end
#app/controllers/registrations_controller.rb
class RegistrationsController < Devise::RegistrationsController
def new
#account = Account.new
super
end
end
#routes
devise_for :users, :controllers => {:registrations => "registrations"}
#view
<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>
<%= devise_error_messages! %>
<div><%= f.label :first_name %><br />
<%= f.text_field :first_name %></div>
<div><%= f.label :last_name %><br />
<%= f.text_field :last_name %></div>
<%= f.fields_for #account do |account_form| %>
<div><%= account_form.label :name %><br />
<%= account_form.text_field :name %></div>
<% end %>
<div><%= f.label :email %><br />
<%= f.email_field :email %></div>
<div><%= f.label :password %><br />
<%= f.password_field :password %></div>
<div><%= f.label :password_confirmation %><br />
<%= f.password_field :password_confirmation %></div>
<div><%= f.submit "Sign up" %></div>
<% end %>

Resources