Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Validates wether a Rails association belongs to the same owner
Ruby
branch: master

Fetching latest commit…

Cannot retrieve the latest commit at this time

Failed to load latest commit information.
lib
spec
.gitignore
.travis.yml
Gemfile
README.md
Rakefile
validates_belongs_to.gemspec

README.md

validates_belongs_to Build Status

Validate your associations to ensure they belong to the same owner. Also works for has_and_belongs_to_many associations.

Usage

Add to your Gemfile:

gem 'validates_belongs_to'

Add the validator to your model:

class Car < ActiveRecord::Base
  validates :warehouse, :belongs_to => :user
  # or you can use validates_belongs_to :warehouse, :user
end

Example code: belongs_to

class User < ActiveRecord::Base
  has_many :warehouses
  has_many :cars
end

class Warehouse < ActiveRecord::Base
  has_many :cars
  belongs_to :user
end

class Car < ActiveRecord::Base
  belongs_to :user
  belongs_to :warehouse
  validates :warehouse, :belongs_to => :user
end

user = User.create
warehouse = user.warehouses.create

user_2 = User.create
warehouse_2 = user_2.warehouses.create

Car.create :warehouse => warehouse # Works fine
Car.create :warehouse => warehouse_2 # Validation failed: Warehouse does not belong to user

Example code: has_and_belongs_to_many

class User < ActiveRecord::Base
  has_many :warehouses
  has_many :cars
end

class Warehouse < ActiveRecord::Base
  has_many :cars
  belongs_to :user
  has_and_belongs_to_many :cars
end

class Car < ActiveRecord::Base
  belongs_to :user
  has_and_belongs_to_many :warehouses
  validates :warehouses, :belongs_to => :user
end

user = User.create
warehouse = user.warehouses.create

user_2 = User.create
warehouse_2 = user_2.warehouses.create

Car.create :warehouses => [warehouse] # Works fine
Car.create :warehouses => [warehouse_2] # Warehouses do not belong to user
Something went wrong with that request. Please try again.