2015-04-08 107 views
0

範圍的關係,我在Rails的兩種型號:創建與軌道4

class User < ActiveRecord::Base 
    enum user_type: [:admin, :normal] 
end 

class Department < ActiveRecord::Base 
end 

包容我寫了下面Rspec的測試:

require 'rails_helper' 

RSpec.describe User, :type => :model do 
    it { should belong_to(:department).conditions(user_type: :admin)} 
end 

我需要什麼,我不知道如何實現這一點。我如何根據其類型創建兩個模型之間的關係?

換句話說,如何才能使這種關係只與類型爲「管理員」的用戶?

鏈接或我看到了類似的問題,並沒有爲我工作,測試仍然失敗

+0

或者'user_type'是'normal'呢? –

回答

1

您可以使用範圍像:

class User < ActiveRecord::Base 
    enum user_type: [:admin, :normal] 
    belongs_to :department, -> { joins(:users).where("users.user_type = ?", 0) } 
end 

Associations are built from Relations,並且可以使用Relation語法自定義它們。在-> { ... }塊內部,您可以使用所有常用的Relation方法。

+0

非常感謝你......現在工作:D – psantos

+0

hi @Arup, 我發現了一個問題...定義這種方式,我的測試通過了...但有一個錯誤:它試圖構建select像這樣:'SELECT「departments」。* FROM「departments」WHERE「departments」。「id」= $ 1 AND「departments」。「user_type」='admin'LIMIT 1' – psantos

+0

請注意'user_type'列只存在於USer表和不在部門表 – psantos