2017-07-30 120 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