Skip to content

Instantly share code, notes, and snippets.

@mfilipe
Created April 21, 2016 17:57
Show Gist options
  • Save mfilipe/86056c7864178e72f768c0b8daca100b to your computer and use it in GitHub Desktop.
Save mfilipe/86056c7864178e72f768c0b8daca100b to your computer and use it in GitHub Desktop.
ActiveRecord::RecordInvalid: Validation failed: User can't be of a different company
class Template < ActiveRecord::Base
belongs_to :company
belongs_to :template_category
belongs_to :user
validates :name, :subject, :body, :company, :template_category, :user, presence: true
validate :recommended_only_admin_user, :template_category_same_company, :user_same_company
private
def recommended_only_admin_user
if recommended and not user.admin?
errors.add(:recommended, 'only admin user can create')
end
end
def template_category_same_company
if not template_category.nil? and not template_category.company.eql? company
errors.add(:template_category, "can't be of a different company")
end
end
def user_same_company
if not user.nil? and not user.admin? and not user.company.eql? company_id
errors.add(:user, "can't be of a different company")
end
end
end
FactoryGirl.define do
factory :template do
name "MyString"
subject "MyString"
body "MyText"
signture "MyText"
recommended false
company
user { build(:user, company: company) }
template_category { build(:template_category, company: company) }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment