Rails关联 - 如何获取和对象而不是整数

时间:2015-01-28 11:59:45

标签: ruby-on-rails activerecord associations

我在Rails中有两个模型。一个用于用户,一个用于可由用户拥有的Jobs。在User模型中,我有一个has_many关联,在Jobs对象中我有一个belongs_to关联。作业有一个owner列,它是所有者的用户ID(通过外键关联)。

User: (id, name, email)

Class User < ActiveRecord::Base
  has_many :jobs, dependent: :destroy, class_name: 'Job', foreign_key: :owner
end

Job: (id, owner, job_code)

Class Job < ActiveRecord::Base
  belongs_to :user, class_name: 'User', foreign_key: :owner
end

这在一个方向上工作正常:User.first.jobs将显示属于该用户的所有作业的列表。不幸的是,如果我尝试用户Job.first.owner,我只会得到用户的id整数,而不是用户对象。我错过了什么,能够选择所有者而无需重新查询数据库以通过ID获取用户?

1 个答案:

答案 0 :(得分:3)

1st Issue:
 Don't use "object" as your model name, this keyword is already reserved. 

假设您有用户模型和工作模型,一个用户有很多工作。

User (id, name, email) Job (id, job_code, owner)

here, the owner column holds the userID to which the job belongs to. 

class User < ActiveRecord::Base
  has_many :jobs, class_name: 'Job', foreign_key: 'owner'
end


class Job < ActiveRecord::Base
  belongs_to :user , class_name: 'User', foreign_key: 'owner'
end

现在:

User.first.jobs #will give you first users jobs. 
Job.first.user #will give you the owner info of the job

希望有所帮助:)