开发者

how to enforce inclusion rules in ActiveRecord associations

I'm new to rails and I have a question on how best to enforce custom rules on my model associations.

For example, suppose I have:

class Person < ActiveRecord::Base
  belongs_to :organization
end

class Organization < ActiveRecord::Base
  h开发者_开发百科as_many :people
end

and now suppose that I only want to allow the Organization.people << Person.new(...) command to succeed if the new Person object is compatible with the other people that were previously added to the Organization. This would entail running a validation check across all the existing elements of Organization.people and deciding whether the new Person could be added or not.

It seems to me that I can do this by overriding all the Organization.people assignment operators (such as << and =) and putting my validation logic in the override routine.

Is this best way to accomplish this?

Thanks!


I think you could put a validation in the Person class. It would run a test against the other people in self.organiation.people. I don't know if I would override the << on the has many relationship only because if you decide to create a person like Person.new(:organization => some_org) your << override would not get used. If the validation lives on the Person class, it would get exercises no matter how you create the person.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜