Tintin81
Tintin81

Reputation: 10207

How to validate that foreign key value belongs to current user?

In my Rails 4 app I have users who can have many companies which in turn can have many people.

When a user creates a new person, how can I validate that he cannot possibly (through browser hacking) select another user's company_id?

I would like to deal with this at the model level, however this doesn't work:

class Person < ActiveRecord::Base

  belongs_to :user
  belongs_to :company

  validates :company_id, :inclusion => { :in => Company.where(:user_id => user_id) }

  ...

end

Thanks for any ideas.

Upvotes: 0

Views: 73

Answers (2)

RAJ
RAJ

Reputation: 9747

You need to pass array of Company IDs to in: like this:

validates :company_id, :inclusion => { :in => Proc.new { |person| Company.where(:user_id => person.user_id).pluck(:id) } }

Upvotes: 1

lazzi
lazzi

Reputation: 445

You need to use proc:

 validates :company_id, :inclusion => { :in => proc { |record| Company.where(:user_id => record.user_id) } }

I hope the syntax is correct, i didn't check it :)

Upvotes: 1

Related Questions