Can someone please explain to me why it seems to ignore the with_options block in this code?
class User < ActiveRecord::Base
attr_accessible :name,:user_type,:policy_num,:address,:city,:state,:zip,:phone,:fax,:email,
:password, :password_confirmation
has_secure_password
has_many :policies
has_many :dealer_forms
before_save {|user| user.email = email.downcase}
before_save :create_remember_token
ZIP_REGEX = /^\d{5}(-\d{4})?$/
EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
COMPLEX_PHONE_REGEX = /^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$/
validates :name, presence: true, length:{in:4..50}
validates :email, presence: true, uniqueness: {case_sensitive: false},format:{with:EMAIL_REGEX}
validates :password, length:{in:6..20}, if: :password
validates :password_confirmation, presence:true, if: :password
validates :user_type, presence: true, inclusion: {in: %w(Dealer Producer System)}
# Validate True User items skip admin users #
with_options :unless => :is_system_user? do |u|
u.validates :policy_num, presence: true
u.validates :address, presence: true
u.validates :city, presence: true
u.validates :state, presence: true, length:{is: 2}
u.validates :zip, presence: true, format:{with:ZIP_REGEX,message: "Not a valid Zip Code"}
u.validates :phone, allow_blank: true, format:{with:COMPLEX_PHONE_REGEX}
u.validates :fax, allow_blank: true, format:{with:COMPLEX_PHONE_REGEX}
end
private
def create_remember_token
self.remember_token = SecureRandom.urlsafe_base64
end
def is_system_user?
user_type == "System" ? true : false
end
end
I have tried the following:
with_options unless: :is_system_user?
with_options unless: Proc.new{|user| user.user_type == "System"}
with_options unless:"user_type = 'System'"
with_options if: "user_type != 'System'"
but for some reason when I try and create a user in the console it still runs the validations inside the block.
Any help would be greatly appreciated. Thanks
Related
I am having some issues creating a record from a relational record. This code creates a new user perfectly however it seems that it skips over creating the user's profile all together. It also throws no errors.
any help would be great.
Model
class User < ActiveRecord::Base
has_one :profile
def self.find_for_facebook_oauth(auth)
if user = User.find_by_email(auth.info.email)
user
else
user = User.create( provider: auth.provider,
uid: auth.uid,
email: auth.info.email,
password: Devise.friendly_token[0,20] )
user.build_profile( username: auth.extra.raw_info.username,
first_name: auth.info.first_name,
last_name: auth.info.last_name,
gender: auth.extra.raw_info.gender,
country: auth.extra.raw_info.locale,
image: auth.info.image )
user
end
end
end
Try user.create_profile instead.http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html
I forgot that in my Profile class I had a validation for username
model
class Profile < ActiveRecord::Base
# Use friendly_id
extend FriendlyId
friendly_id :username, use: :slugged
belongs_to :users
mount_uploader :image, ProfileImageUploader
validates :username, presence: true, length: {maximum: 16} # <~~
validates :first_name, presence: true, length: {maximum: 255}
validates :last_name, presence: true, length: {maximum: 255}
validates :gender, presence: true, inclusion: %w(male female)
end
My OmniAuth was not giving the username therefore it was rolling back the commit.
I am trying to implement a user authentication system inside rails, this is my model:
class User < ActiveRecord::Base
attr_accessible :id, :email, :name, :password, :created_at, :updated_at
has_secure_password
before_save { email.downcase! }
validates :email, presence: true, :uniqueness => { :case_senstive => false }
validates :name, presence: true
validates :password, presence: true, length: { minimum: 6 }
end
Running in the console i can read the User table successfully, then when i try to create a record:
User.new(:name => "A", :email => "a#a.a", :password => "password")
running valid on it retrurns true, but when saving the record, i get error:
users.password may not be NULL
Extracting the password out of the hash works fine.
What is the problem?
Thanks
Where are you setting :password_confirmation? The example in the docs suggests you need it.
http://api.rubyonrails.org/classes/ActiveModel/SecurePassword/ClassMethods.html
Main problem is in has_secure_password. If you are using that you should have string field :password_digest (it's where your encrypted password will be saved). And you need delete field :password and your validator of presence for that too. After add gem 'bcrypt-ruby', '~> 3.0.0' .
And now that should work
user = User.new(:name => "A", :email => "a#a.a",
:password => "password", :password_confirmation => "password")
But better use great gem https://github.com/plataformatec/devise . It has everything you need.
NEW ADDED
you should have attr_accessible for :password_confirmation too and that field should be used in your form.
more info about has_secure_password
I have a model called "Store" and it has an attribute "City" which has a "State" associated to it. I'm creating a store's filter by state and/or city with simple_form. The problem is, how to make simple_form does not associate the "State" to "Store" ?
class State < ActiveRecord::Base
attr_accessible :name
has_many :cities
end
class City < ActiveRecord::Base
attr_accessible :name
belongs_to :state
has_many :stores
end
class Store < ActiveRecord::Base
attr_accessible :latitude, :longitude, :description, :city_id
validates :city, :presence => true
validates :description, :presence => true, :length => {:maximum => 500}
validates :latitude, :presence => true
validates :longitude, :presence => true
belongs_to :city
end
<%= simple_form_for #store, :html => { :class => 'add-store-form', :style => "display:none;" } do |f| %>
<table border="0">
<tr>
<td>Estado:</td>
<td>
<%= f.collection_select :state, State.all, :include_blank => false, :label => false,
:input_html => { :id => "state_id", :name => "state_id" } %>
</td>
</tr>
.
.
This way is not working.
How can I do this?
Thanks in advance!
This is not the answer to you question, but improve your code by doing:
validates :city, :latitude, :longitude, :description, presence: true
validates :description, length: {maximum: 500}
And I recommend using Strong Parameters (Default in rails 4) to define with attributes can be assigned from forms instead of attr_accessible option
I'm running rails 3.2.5 with the latest Devise gem. And i have a user class that is related to an Actor class. There is a field called slug that validates fine if I use the following syntax...
validates :slug, :presence => true, :length => { :maximum => 50 }
But if I place the extra uniqueness argument
validates :slug, :presence => true, :length => { :maximum => 50 }, :uniqueness => true
it throws an error...
NoMethodError in Devise::RegistrationsController#update
undefined method `text?' for nil:NilClass
I'm not sure what is causing such.
I should also mention that in my user model class I have the following...
attr_accessible :name, :email, :password, :password_confirmation, :language, :remember_me, :profile_attributes, :admin, :slug
And that in my config file I have
config.active_record.whitelist_attributes = false #not standard nor recommended I know
I had the same problem and was able to get around it by separating out validates_uniqueness_of by itself. So for me
validates :username, :presence, uniqueness: { case_sensitive: false }
throws the same error (undefined method 'text?'). while changing to
validates_presence_of :username
validates_uniqueness_of :username, { case_sensitive: false }
works just fine.
I have this Rails 3.2 application running fine. I installed Rolify by following the steps below:
Add gem "rolify" to the Gemfile
Run bundle install
Run rails g rolify:role
Check the new migrations, the new files and the modified files (generated/modified by the command above).
Run rake db:migrate
At this point, I try to create/edit a User and I get the following error:
NoMethodError in UsersController#create
undefined method `user_id' for #<User:0x007f8f21f168e8>
Note that before I installed Rolify, everything was working fine, so the problem comes from Rolify.
Here are the migration, the new file and the modified file in question:
The new migration:
class RolifyCreateRoles < ActiveRecord::Migration
def change
create_table(:roles) do |t|
t.string :name
t.references :resource, :polymorphic => true
t.timestamps
end
create_table(:users_roles, :id => false) do |t|
t.references :user
t.references :role
end
add_index(:roles, :name)
add_index(:roles, [ :name, :resource_type, :resource_id ])
add_index(:users_roles, [ :user_id, :role_id ])
end
end
The new model:
class Role < ActiveRecord::Base
has_and_belongs_to_many :users, :join_table => :users_roles
belongs_to :resource, :polymorphic => true
end
The modified model:
class User < ActiveRecord::Base
rolify
has_secure_password
has_many :issues
acts_as_tenant(:client)
attr_accessible :email, :password, :password_confirmation, :username
validates :username, presence: true,
length: { within: 4..50 },
format: { with: /(?:[\w\d]){4,255}/ }
validates_uniqueness_to_tenant :username, case_sensitive: false
validates :email, presence: true,
uniqueness: { case_sensitive: false },
length: { within: 8..255 },
format: { with: /^[-a-z0-9_+\.]+\#([-a-z0-9]+\.)+[a-z0-9]{2,4}$/i }
validates :password, presence: true, on: :create,
confirmation: true,
length: { within: 4..255 }
validates :password_confirmation, presence: true, on: :create
# NOTE: Used by SimpleForm to display the dropdown proerply
def to_label
"#{username}"
end
end
You can find the rest of the files in the project in the Github repo
Does anyone have a clue where the error comes from please?
This error is happening because the acts_as_tenant is (mistakenly) creating a validation for a user_id field on your User model. You can see this validator if you run this code inside rails c:
User._validators
I would recommend to switch to the apartment gem which appears to be more maintained than acts_as_tenant.