validates_uniqueness_of when updating car.number - ruby-on-rails

When updating car info, the validation process fails because I have validates_uniqueness_of :number
class Car < ActiveRecord::Base
validates :number,numericality: true, length: {is: 7 }
validates :number, :name, presence:true
validates_uniqueness_of :number, :message => "מספר רכב זה קיים במערבת"
belongs_to :owner
has_many :visits
end
I need validation to pass, if the original value was not changed, validation on_create would not help since I still need validation when updating.
Any help would be really appreciated.

This will work for you :
validates :number, :uniqueness => {:scope => :number}, :message => "מספר רכב זה קיים במערבת"
OR
validates_uniqueness_of :number, :message => "מספר רכב זה קיים במערבת", :scope => :number

Related

Rails: How to validate a primary flag on a one to many relationship

Decided to update the information here based upon the feedback I have received to date and what I currently have setup.
I have been trying to work out the best way to solve this issue but so far I am not coming up with an answer. I have two tables: customers and credit_cards. A customer can have many credit_cards and a credit_card belongs to a customer. Also, a customer can have many addresses and an addresses belongs to a customer.
In my creditcard table I have a column that indicates if a particular credit card is primary. The column name is primary. A customer can have many creditcards but only ONE can be primary.
I was hoping that this could be done via validations but so far I am coming up empty. I've done numerous searches but nothing seems to work :(
The following post seems to indicate how this can be done but I couldn't get this to work:
Validation Solution?
My customer.rb model file is as follows. It's not the entire code in there but the relevant parts.
class Customer < ActiveRecord::Base
track_who_does_it :creator_foreign_key => "created_by", :updater_foreign_key => "updated_by"
has_many :addresses, :dependent => :destroy
accepts_nested_attributes_for :addresses, :reject_if => lambda { |a| a['name'].blank? }, :allow_destroy => true
has_many :creditcards, :dependent => :destroy
accepts_nested_attributes_for :creditcards, :reject_if => lambda { |a| a['name'].blank? }, :allow_destroy => true
has_one :primary_creditcard, ->{ where(primary: "1") }, class_name: Creditcard, autosave: true
validates :addresses, presence: true
validates :creditcards, presence: true
validates :primary_creditcard, presence: true
end
My creditcard.rb model file is as follows.
class Creditcard < ActiveRecord::Base
track_who_does_it :creator_foreign_key => "created_by", :updater_foreign_key => "updated_by"
belongs_to :customer
validates :name, presence: true, length: { maximum: 30}
validates :card_type, presence: true
validates :card_number, presence: true
validates :card_exp, presence: true
validates :card_code, presence: true
end
When I create a new customer with an address and a credit card I always get an validation error message that states the following:
Primary creditcard can't be blank
I would appreciate any help on this.
As per the request, adding in the code from the controller that saves the data:
if #customer.update_attributes(customer_params)
flash[:success] = 'Member was successfully updated.'
else
flash[:error] = "Member was not updated, please see errors."
end
The above is in the update part of the customer controller.
Also, for reference, the customer_params is defined as follows:
def customer_params
params.require(:customer).permit(:first_name, :last_name, :sex, :dob, :cell_phone, :work_phone, :home_phone, :other_phone, :email1, :email2, :referred_via_id,
:referred_cust_id, :cust_notes,
addresses_attributes: [:id, :customer_id, :name, :line1, :line2, :line3, :city, :county, :state, :zip, :billing, :delivery, :addr_notes],
creditcards_attributes: [:id, :customer_id, :name, :card_type, :card_number, :card_exp, :card_code, :primary])
end
You could add an additional relation called primary_creditcard and validate it's presence
class Customer < ActiveRecord::Base
has_many :credit_cards
has_one :primary_creditcard, ->{ where(primary: true) }, class_name: CreditCard
validates :primary_creditcard, presence: true
end

Scopes doesn't work with STI

I want to do STI in Rails.
class AbstractUser < ActiveRecord::Base
self.table_name = 'users'
belongs_to :organization, :inverse_of => :users
# reporter user
has_many :requests, :dependent => :destroy
# startup user
has_many :responses, :dependent => :destroy
has_many :startup_requests, :through => :responses, :source => :request
scope :reporters, where(:type => 'Reporter')
scope :startup_employees, where(:type => 'Startup')
scope :on_waitlist, where(:waitlist => true)
scope :not_on_waitlist, where(:waitlist => false)
end
require 'rfc822'
class User < AbstractUser
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :confirmable
validates :name, :presence => true
validates :surname, :presence => true
validates :title, :presence => true
validates :password, :presence => true, :length => { :minimum => 8 }
validates :email, :presence => true, :format => { :with => RFC822::EMAIL_REGEXP_WHOLE }
attr_accessible :name, :surname, :title, :organization,
:email, :password, :fullname
end
require 'rfc822'
class UserForAdmin < AbstractUser
validates :email, :presence => true, :format => { :with => RFC822::EMAIL_REGEXP_WHOLE }
validates :organization_id, :presence => true
attr_accessible :name, :surname, :title, :organization, :email,
:password, :fullname, :password_confirmation, :type,
:organization_id, :waitlist, :invitation_token
end
And there is some problem with these scopes.
Couldn't find UserForAdmin with id=7 [WHERE "users"."type" IN ('UserForAdmin') AND "users"."waitlist" = 'f']
I also tried to put these scopes in UserForAdmin instead of AbstractUser with the same result. I (probably) need scopes instead of custom methods, because I use them in ActiveAdmin. How can I solve this?
If you don't want to receive all users, you need to query with the base class. In a simpler example:
class Animal < ActiveRecord::Base
end
class Dog < Animal
end
class Cat < Animal
end
Dog.create
Cat.create
Animal.all
=> [dog, cat]
Dog.all
=> [dog]
Cat.all
=> [cat]
So, in your case, you'd want to:
AbstractUser.not_on_waitlist.find(params[:id])
If this user is a UserForAdmin you'll receive an object of class UserForAdmin. If it's just a user, you'll receive an object of class User

Model.create() throws errors with readonly attributes

I have the following model in rails (simplified):
class Phone < ActiveRecord::Base
include ActiveModel::Validations
belongs_to :user
belongs_to :brand
attr_readonly :user, :brand
attr_accessible :model, :phone_number
validates :user, :presence => true
validates :brand, :presence => true
validates :model, :presence => true
validates :phone_number, :presence => true
end
According to the documentation, attr_readonly should allow attributes to be set at creation, but not at update.
However, when I do this:
Phone.create(:user => <existing_user>, :brand => <existing_brand>, :model => "Galaxy", :phone_number => "555-433-5678")
I get this error:
Can't mass-assign protected attributes user, brand
What am I missing?
If you want to assign a user and a brand association like that, you must define them as being accessible attributes:
attr_accessible :user, :brand
Otherwise, you can assign them like this:
Model.create({:user => user, :brand => brand }, :without_protection => true)

Rails Validate Uniqueness Isn't Working

Model Code (Attempting to require uniqueness for embed_code)
https://gist.github.com/1427851:
class Link < ActiveRecord::Base
validates :embed_code,
:format => {:with => /^<object type|^<embed src|^<object width|^<iframe src|^<object height|^<iframe width|^<embed id|^<embed width|^<object data|^<div|^<object id/i, :message => "Invalid Input"},
:uniqueness => true
attr_accessible :title, :embed_code, :score
after_initialize :calculate_score, :favs_count
attr_accessor :score, :fav_count
validates :title, :length => { :in => 4..45, :message => "Must be between 4 & 45 characters"}
before_save :resize
has_many :favorites
has_many :favorited, :through => :favorites, :source => :user
belongs_to :user
I've tried validates_uniqueness_of :embed_code and disabling (commenting out) non-critical components of the model such as :before_save :resize

Validating content of the attributes to not be the same

I am trying to write a unit testing for a User model in Ruby on Rails. I am using authlogic and need to check that the first_name and last_name of the user model attributes are not the same when the user is registering.
This is my user model:
class User < ActiveRecord::Base
acts_as_authentic do |c|
c.login_field= :username
end
has_many :memberships, :class_name => "Project::Membership"
has_many :projects, :through => :memberships
has_one :profile
validates :email, :presence => true, :uniqueness => true
validates :username, :presence => true, :uniqueness => true
validates :first_name,:presence => true
validates:last_name, :presence => true
validates :title, :presence => true
validates :password, :presence => true
validates :password_confirmation, :presence => true
validates :gender, :presence => true
# Custom validator
validates :first_name, :last_name, :different_names => true
As you can see, I tried to create a custom validator creating a new file in /lib/different_names_validator.rb with a class called DifferntNamesValidator, but couldn't get it, as I got the following error: Unknown validator: 'different_names' (ArgumentError)
Thanks in advance!
Hi Try to include this module in your model

Resources