I'm trying to create a register form in Ruby on Rails.
My form current form looks like this:
<%= form_for #util, :remote => true do |f| %>
<div class="register-form">
<div class=form-name>
<span>Name </span>
<span><%= f.text_field :name %></span>
</div>
<div class=form-surname>
<span>Surname </span>
<span><%= f.text_field :surname %></span>
</div>
<div class=form-email>
<span>E-mail </span>
<span><%= f.text_field :email %></span>
</div>
<div class=form-password>
<span>Password </span>
<span><%= f.text_field :password %></span>
</div>
<div class="submit">
<%= f.submit "Register" %>
</div>
</div>
<% end %>
My controller for creating it looks like this:
def create
#user = User.new(params[:util])
#user.password = encrypt_password(#user.password)
if #user.save!
respond_to do |format|
format.json { render :partial => "partials/form.html.erb", :task => #task }
end
end
end
When I check the variables during debug I can see that the #user.password comes nil, but if I check it manually as #user.password it gives me the content that I input.
When I try to save the new user in the database it always has a nil password.
Any sugestion on why the password always comes nil even if the params and encrypt are correct?
Edit:
Thanks for the help with the code and the password security field issue. I had forgotten about it, after taking a look into the model after the replies I noticed something off:
class User < ActiveRecord::Base
attr_accessible :email, :name, :password, :surname
has_and_belongs_to_many :projects
attr_accessor :password
After removing attr_accessor I managed to acess the password and save in the DB without issues.
Please change:
<%= f.text_field :password %>
To:
<%=f.password_field :password%>
Also:
#user.password = encrypt_password(#user.password)`
should be something like:
#user.password = encrypt_password(params[:util][:password])
Related
So I have a basic sign up, sign in site with username and password. I don't want to use recaptcha and was wondering whether i can create my own?
So have for example 'what colour is an orange'.
I was wondering how you could integrate this (if you can that is) into the form_for as it wouldn't be part of the #user object and throws an error.
Here is the controller
def new
#user = User.new
#captcha = Captcha.find(rand(1..3))
end
def create
#user = User.new(user_params)
if #user.save
session[:user_id] = #user.id
redirect_to root_path
else
render 'new'
end
end
private
def user_params
params.require(:user).permit(:username, :password, :release_pin)
end
Here is the view
<div class="sign-in-form">
<%= form_for #user do |form| %>
<div class="form-text">
<%= form.label :username %> <br>
<%= form.text_field :username %>
</div>
<br>
<div class="form-text">
<%= form.label :password %> <br>
<%= form.text_field :password %>
</div>
<br>
############## this here obviously throws
an error but this is the kind of thing i would want #########
<div class="form-text">
<p> <%=#captcha.question%> </p>
<%= form.text_field :captcha_answer %>
</div>
<div class="form-text">
<%= form.submit "Submit" %>
</div>
I've looked into nested forms but don't think that's the correct answer... but I could wrong as I'm only a beginner. thanks
I want to send multiple invitations at a time using devise-invitable gem.
new.html.erb
<h2>
<%= t "devise.invitations.new.header" %>
</h2>
<%= form_for resource, :as => resource_name, :url => invitation_path(resource_name), :html => {:method => :post} do |f| %>
<%= devise_error_messages! %>
<div>
<% resource.class.invite_key_fields.each do |field| -%>
<p><%= f.label field %><br />
<%= f.email_field field, placeholder: "Invitation email" %></p>
<% end -%>
<%= f.collection_select(:role_id, Role.all, :id, :role_name, :prompt => true) %>
</div>
<p>
<%= f.submit t("devise.invitations.new.submit_button") %>
</p>
<% end %>
my controller:-
class Users::InvitationsController < Devise::InvitationsController
def create
exit
if params[:user][:email]== "" || params[:user][:role_id] == ""
flash[:alert]="Please enter email first and Select any role for invitees"
redirect_to new_user_invitation_path
else
if User.invite!(:email => params[:user][:email], :company_id => current_user.id, :type => 'Employee', :role_id => params[:user][:role_id])
flash[:notice]="Invitation is send successfully."
redirect_to new_user_invitation_path
else
flash[:alert]="Invitation is not send."
redirect_to new_user_invitation_path
end
end
end
end
I think one solution is to pass comma separated emails in invite method but how can I pass it? I really don't know how.
If you have any other solution then please tell me.
Thanks.
i trouble with this problem but finally i got solution to send multiple invitation email at a time.
below i explain my code that how i become possible this.
here is my html view.
new.html.erb
<h2>
<%= t "devise.invitations.new.header" %>
</h2>
<%= form_for resource, :as => resource_name, :url => invitation_path(resource_name), :html => {:method => :post} do |f| %>
<%= devise_error_messages! %>
<div>
<% resource.class.invite_key_fields.each do |field| -%>
<%= f.label field %><br />
<%= f.email_field field, name: "user[email][]", placeholder: "Invitation email", required: true %></p>
<div id="createNewTextbox" >
</div>
<a id="btnLinkCreate" href="#" onClick="create_new();">
+ INVITE MORE
</a>
<% end -%>
</div>
<p>
<%= f.submit t("devise.invitations.new.submit_button") %>
</p>
<% end %>
in this i take one text-box by-default with name : "user[email][]" (it is important because using this rails automatically create email array and send in params whene you submit form )
i also generate dynamic text-box using JavaScript and it will create below div when click on invite more link button :
<div id="createNewTextbox" >
</div>
<a id="btnLinkCreate" href="#" onClick="create_new();">
+ INVITE MORE
</a>
here is my dynamic text-box code of JavaScript.
$('#createNewTextbox').append('<input type="email" id="email'+i+'" name="user[email][]" placeholder="Invitation email" required/>');
now you can see that i give same name to dynamic text-box (name="user[email][]"), so rails automatically create hash array like this:
"user" => { "email" => { "email-1","email-2","email-3"... } }
now this hash array is pass in create method in which we fetch every email from params and give it to invite method to send the invitation.
my controller :-
class Users::InvitationsController < Devise::InvitationsController
def create
params[:user][:email].each do |email|
User.invite!(:email => email)
end
end
end
thats it...
if still you have any query then tell comment me.
I am creating an application through which a user will be able to create an account. When they create an account, in the same form they will be able to create an organization that will then be tied to their user. Once that user has created their account (and an organization) other users will be able to create an account and use an "access code" to join that organization as well. Looking at the code may explain it better.
The reason i'm posting on SO is because i have a feeling there is a better / more efficient way to do it than what i am currently doing. I'm using nested_forms (maybe not correctly) and i don't think i'm doing the associations the right way because, for example, i haven't been able to get the edit form to fill out the organization fields.
I am using sorcery for the authentication as well.
users_controller.rb
def new
#user = User.new
end
def create
#user = User.new(user_params)
if params[:user][:organization][:name].blank?
flash.now[:error] = "You must specify an organization name."
render :new
else
if params[:user][:organization][:access_code].blank?
# create new organization
#access_code = "#{SecureRandom.urlsafe_base64(16)}#{Time.now.to_i}"
#organization = Organization.create(:name => params[:user][:organization][:name], :access_code => #access_code)
#user.organization_id = #organization.id
#user.is_admin = true
else
# try and add someone to an organization
#organization = Organization.find(:all, conditions: ["name = ? AND access_code = ?", params[:user][:organization][:name], params[:user][:organization][:access_code]])
if #organization.empty?
flash.now[:error] = "No organization has been found with that name and access code."
render :new
return
else
#user.organization_id = #organization.first.id
end
end
if #user.save
user = login(#user.email, params[:user][:password])
if user
flash[:success] = "Your account has been successfully created!"
redirect_to admin_dashboard_path
end
else
flash.now[:error] = "Something went wrong! Please try again."
render :new
end
end
end
def edit
#user = User.find(params[:id])
end
def update
#user = User.find(params[:id])
if #user.is_admin?
if params[:user][:organization][:name].blank? && params[:user][:organization][:name] != #user.organization.name
params[:user][:organization][:name] = #user.organization.name
end
if params[:user][:organization][:access_code].blank? && params[:user][:organization][:access_code] != #user.organization.access_code
params[:user][:organization][:access_code] = #user.organization.access_code
end
#organization = Organization.find(params[:user][:organization_id])
#organization.name = params[:user][:organization][:name]
#organization.access_code = params[:user][:organization][:access_code]
#organization.save
end
if #user.update(user_params)
flash[:success] = "Your settings have been updated!"
redirect_to edit_admin_user_path(#user.id)
else
flash.now[:error] = "Something went wrong! Please try again."
render :edit
end
end
private
def user_params
params.require(:user).permit(:organization_id, :email, :password, :password_confirmation, :full_name, :remember_me, {:organization_attributes => [:name, :website, :description, :access_code]})
end
users.rb
class User < ActiveRecord::Base
authenticates_with_sorcery!
belongs_to :organization
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates_presence_of :full_name
validates_presence_of :email
validates_uniqueness_of :email, :on => :create
validates_format_of :email, :with => VALID_EMAIL_REGEX, :on => :create
validates_presence_of :password, :on => :create
validates_confirmation_of :password
end
organization.rb
class Organization < ActiveRecord::Base
authenticates_with_sorcery!
has_many :users, :dependent => :destroy
accepts_nested_attributes_for :users
validates_presence_of :name
end
new.html.erb
<% provide(:title, 'Create a User') %>
<h1>Create a User</h1>
<p>Use the form below to create an account.</p>
<%= nested_form_for([:admin, #user], html: {role: "form"}) do |f| %>
<%= render "shared/error_messages", obj: #user %>
<fieldset>
<legend>User Information</legend>
<div class="form-group">
<%= f.label :full_name, "Full Name" %>
<span class="help-block">How should others see you?</span>
<%= f.text_field :full_name, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :email %>
<span class="help-block">Your email address is used as your login.</span>
<%= f.text_field :email, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :password %>
<%= f.password_field :password, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :password_confirmation, "Confirm Password" %>
<%= f.password_field :password_confirmation, class: "form-control" %>
</div>
</fieldset>
<%= f.fields_for :organization do |o| %>
<fieldset>
<legend>Associated Organization</legend>
<div class="form-group">
<%= o.label :name, "Organization Name" %>
<span class="help-block">This is the name of the organization you are a part of.</span>
<%= o.text_field :name, class: "form-control" %>
</div>
<div class="form-group">
<%= o.label :access_code, "Organization Access Code" %>
<span class="help-block">Leaving this field blank will setup a new organization.</span>
<%= o.text_field :access_code, class: "form-control" %>
</div>
</fieldset>
<% end %>
<div class="form-actions">
<%= f.submit "Create Account", class: "btn btn-primary" %>
<%= link_to "Cancel", :back, class: "text-btn" %>
</div>
<% end %>
edit.html.erb
<% provide(:title, "Edit User: #{#user.full_name} (#{#user.organization.name})") %>
<h1>Edit User: <%= #user.full_name %> (<%= #user.organization.name %>)</h1>
<p>Use the form below to manage your account.</p>
<%= nested_form_for([:admin, #user], html: {role: "form"}) do |f| %>
<%= render "shared/error_messages", obj: #user %>
<fieldset>
<legend>User Information</legend>
<div class="form-group">
<%= f.label :full_name, "Full Name" %>
<span class="help-block">How should others see you?</span>
<%= f.text_field :full_name, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :email %>
<span class="help-block">Your email address is used as your login.</span>
<%= f.text_field :email, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :password %>
<%= f.password_field :password, placeholder: "leave blank to keep password unchanged", class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :password_confirmation, "Confirm Password" %>
<%= f.password_field :password_confirmation, class: "form-control" %>
</div>
</fieldset>
<% if #user.is_admin? %>
<%= f.fields_for :organization do |o| %>
<fieldset>
<legend>Associated Organization</legend>
<div class="form-group">
<%= o.label :name, "Organization Name" %>
<span class="help-block">This is the name of the organization you are a part of.</span>
<%= o.text_field :name, class: "form-control", value: #user.organization.name %>
</div>
<div class="form-group">
<%= o.label :access_code, "Organization Access Code" %>
<span class="help-block">Leaving this field blank will setup a new organization.</span>
<%= o.text_field :access_code, class: "form-control", value: #user.organization.access_code %>
</div>
</fieldset>
<% end %>
<%= f.hidden_field :organization_id %>
<% end %>
<div class="form-actions">
<%= f.submit "Update User", class: "btn btn-primary" %>
<%= link_to "Cancel", :back, class: "text-btn" %>
</div>
<% end %>
Ok, those are all the files making it happen. Now, i have the application doing almost everything i need it to do but this doesn't feel like production-level code to me.
One issue i know i am having is that if a user types something in the organization field and nothing else the controller will create and save the organization and then render the form back with the user validation errors. I don't want it to save the organization if there are validation errors in the user model.
I'm really just asking for advice if there is a better way of doing what i am trying to do. If you can't tell exactly what i'm trying to do with this code or have any questions please let me know!
Take a look at this post: http://blog.codeclimate.com/blog/2012/10/17/7-ways-to-decompose-fat-activerecord-models/
Of particular interest will be the section on "3. Extract Form Objects".
I'm new in rails and currently trying to create an app but I can't seem to make it work. Here's my setup in model.
class User < ActiveRecord::Base
has_one :doctor, dependent: :destroy
accepts_nested_attributes :doctor
end
class Doctor < ActiveRecord::Base
belongs_to :user, :dependent => :destroy
end
In my users_controller, here's my code:
class UsersController < ApplicationController
def show
#user = current_user
# render text: #user.inspect
end
def new
#user = User.new
#user.build_doctor`
end
def create
# binding.pry
#user = User.new(user_params)
if #user.save
sign_in #user
redirect_to dashboard_path
else
render 'new'
end
end
private
def user_params
params.require(:user).permit(:role, :lastname, :firstname, :middlename, :email, :password, :password_confirmation, :doctor_attributes => [:institution, :license_number])
end
end
And my view:
<ul id="cbp-bislideshow" class="cbp-bislideshow">
<li>
<%= image_tag "blur1.jpg" %>
</li>
<li>
<%= image_tag "blur2.jpg" %>
</li>
</ul>
<% provide(:title, 'Sign Up') %>
<%= form_for(#user) do |f| %>
<div class="sign-up-wrapper divided-wrapper cf">
<div class="left-section">
<h3 class="section-title">JOIN US AND LET'S CHANGE THINGS</h3>
<div class="row">
<div class="w49 pull-left">
<%= f.text_field :firstname, class: "input-text personal ", placeholder: 'FIRSTNAME' %>
</div>
<div class="w49 pull-right">
<%= f.text_field :lastname, class: "input-text personal", placeholder: 'LASTNAME' %>
</div>
<%= f.hidden_field :role, value: :doctor %>
</div>
<div class="row">
<%# f.text_field :specialization, class: "input-text personal ", placeholder: 'SPECIALIZATION' %>
</div>
<%= f.fields_for :doctors do |p| %>
<div class="row">
<%= p.text_field :institution, class: "input-text personal ", placeholder: 'INSTITUTION' %>
</div>
<div class="row">
<%= p.text_field :license_number, class: "input-text personal ", placeholder: 'LICENSE NUMBER' %>
</div>
<% end %>
<span class="remind bottom-message"> ONCE INSIDE DON'T FORGET TO UPDATE YOUR PROFILE WITH MORE DETAILS </span>
</div>
<div class="right-section">
<h3 class="section-title"></h3>
<div class="row">
<%= f.text_field :email, class: "input-text personal ", placeholder: 'EMAIL' %>
</div>
<div class="row">
<%= f.password_field :password, class: "input-text personal ", placeholder: 'PASSWORD' %>
</div>
<div class="row">
<%= f.password_field :password_confirmation, class: "input-text personal ", placeholder: 'CONFIRM PASSWORD' %>
</div>
<div class="row cf">
<%= f.submit class: 'btn-join btn', value: 'JOIN NOW' %>
</div>
<div class="row">
SIGN UP WITH FACEBOOK / TWITTER ACCOUNT?
</div>
</div>
</div>
<% end %>
Everytimie I execute these pieces, only the user model gets populated but not the doctors table? Is there something wrong on my code?
EDIT
Changed doctors_attributes to doctor_attributes
changed #user.doctor.build`to #user.build_doctor
In the logs. I saw this error ---> Unpermitted parameters: doctors
So in theory, I think we know what's the problem, but I don't know how to fix this in the strong_parameters. Haven't tried a strong_parameter with accepted_nested_attributes_for in rails yet and this is my first time. Any solution?
In the fields_for, replace :doctors with :doctor. Remember that you're doing a 1 to 1 relationship.
In your user_params model, the attribute doctors_attributes should be doctor_attributes since it's a has_one relationship. If it was a has_many relationship, it would be doctors_attributes. The part before _attributes would be whatever the association is named.
Another note: If you want to be able to update the doctor from the user form, you should also include the id in the doctor_attributes array. Though now that I think of it, it might only be a requirement on has_many nested associations. I've never tried doing a has_one without including the id.
I'm trying to set up a simple Roles model for my site. Users can have any number of roles. Right now I'm setting it up to be a hidden field on the signup form. The problem I'm running into is that in my nested form the role type isn't being saved. An entry with the uid is being created in the roles table but that's about it. The relevant code is below. Any help would be appreciated.
== Schema Information
Table name: roles
id :integer not null, primary key
user_id :integer
role :string(255)
created_at :datetime not null
updated_at :datetime not null
Heres the create method from my users controller...
def create
#user = User.new(params[:user])
if #user.save
#role = #user.roles.new(user_id:#user.id, role:params[:role])
flash[:success] = "Thanks for singing up for the Auditions App, any audition invitations will be visible on this page"
#need to add the role guest to user roles
redirect_to #user
else
render 'new'
end
end
Heres the form....
<div class="span10 offset1 ajax-form">
<%= form_for(#user, :html => {:class => 'well'}) do |f| %>
<h3>Guest Account Signup</h3>
<%= render 'shared/error_messages' %>
<div class="pull-left form-field"><%= f.label :first_name %>
<%= f.text_field :first_name, :class => 'span4' %></div>
<div class="pull-left form-field"><%= f.label :last_name %>
<%= f.text_field :last_name, :class => 'span4' %></div>
<div class="pull-left form-field"><%= f.label :email %>
<%= f.text_field :email, :class => 'span4' %></div>
<div class="pull-left form-field span4"></div>
<div class='clear'></div><!--close .clear-->
<div class="pull-left form-field"><%= f.label :password %>
<%= f.password_field :password, :class => 'span4' %></div>
<div class="pull-left form-field"><%= f.label :password_confirmation, "Confirm Password" %>
<%= f.password_field :password_confirmation, :class => 'span4' %></div>
<div class="form_row pull-left form-field">
</div>
<%= f.hidden_field :role, :value => 'guest' %>
<%= f.submit "Create my account", :class => "btn btn-large btn-primary pull-left form-field" %>
<div class='clear'></div><!--close .clear-->
<% end %>
As #Arpit comments - get rid of the hidden :user_id tag. It's only confounding the attribute setter.
And I don't think building multiple roles using roles.new() (is that the same as roles.build()?) is going to cut it. You'll need to break out the separate roles' parameters and add them one at a time. Or you can grab them in one go like this:
selected_roles = Role.find_all_by_id(params[:roles])
#user.roles = selected_roles
This would assume that you are using role ids in your form, but you aren't for some reason...