Rails ActiveRecord验证深层关系

时间:2014-04-18 19:21:04

标签: ruby-on-rails activerecord

可以有很多Organisations

User属于Organisation

App属于Organisation

Env属于App

创建Env并选择App

我可以撰写哪种validates来检查App是否属于与Organisation相同的current_user

2 个答案:

答案 0 :(得分:0)

User.current是描述为here

的模式
validate :app_must_belong_to_the_same_organisation_as_user

def app_must_belong_to_the_same_organisation_as_user
  unless User.current.organisation == app.organisation
    errors.add(:base, "User's and app's organisations mismatch!")
  end
end

答案 1 :(得分:0)

#app/models/app.rb
Class App < ActiveRecord::Base
    belongs_to :organisation

    validates :app_user_organisation?

    private

    def app_user_organisation?
        organization == [[current_user]] #-> still working out current user
    end
end