Reputation: 10207
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
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
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