2017-07-30 116 views
0
class User < ApplicationRecord 
    has_many :user_positions 
    has_many :job_titles, through: :user_positions 

class JobTitle < ApplicationRecord 
    has_many :user_positions 
    has_many :users, through: :user_positions 

class UserPosition < ApplicationRecord 
    belongs_to :user 
    belongs_to :job_title 

鑑於上述模型ActiveRecord關聯,我想查詢一個JOBTITLE,然後與JOBTITLE像這樣返回所有用戶:活動記錄關聯 - 錯誤w has_many:通過關聯?

JobTitle.where(id: 6).users 

這示數W¯¯

undefined method `users' for #<JobTitle::ActiveRecord_Relation 

我究竟做錯了什麼?

感謝

+0

'where'會給你一個ActiveRecordRelationship,許多對象,'find'會給你一個。 –

回答

1

使用findfind_byfind引發RecordNotFound如果沒有與此ID的記錄):

JobTitle.find_by(id: 6).users 

這只是如何has_many作品:一個模型有多種型號。 Where返回一個關係,例如, JobTitle.where('id > ?', 1)將返回一組記錄。在你的情況下,where返回一個記錄的關係,就像一個包含一個元素的數組。

1

的代碼JobTitle.where(ID:6)返回記錄集,最好的辦法是使用找到方法。

就試試這個:

JobTitle.find(6).users 

或者

JobTitle.where(id: 6).first.users