Rails has_many 和 belongs_to 中的 :foreign_key

bwlinux · 2014年05月29日 · 最后由 bwlinux 回复于 2014年05月29日 · 7276 次阅读

model 里边的 has_many 和 belongs_to 在表都是用 model_id 的时候,容易理解。我想研究一下用 foreign_key 的方法,这两个表,都不使用 id 作为 primary key,这个时候,我的头脑就一团糊涂了。不知道怎么写 model。下面的例子,我故意不用 id。

有两个表,authors(aid, aname)papers(pid, a_id, pname)

class Paper < ActiveRecord::Base
  self.primary_key = 'pid'
  belongs_to :author
end
class Author < ActiveRecord::Base
  self.primary_key = 'aid'
  has_many :papers, foreign_key: 'a_id'
end

这个时候,我可用Author.find(1).papers得到作者的文章列表,但是Paper.find(2).author不能够返回 paper 的 author。我上面的 code,错误在什么地方。 我很疑问下面的用法,正确不正确?,如果正确,表示什么意思,在什么场合会用到。

class Author < ActiveRecord::Base
  self.primary_key = 'aid'
  has_many :papers, foreign_key: 'a_id', primary_key: 'pid'
end

谢谢。

应该是两边都需要指派 foreign_key, 试着在 belongs_to 上加上。

self.primary_key 默认主键 默认 ID

:primary_key

Specify the method that returns the primary key of associated object used for the association. By default this is id.

但是 Paper.find(2).author 不能够返回 paper 的 author

belongs_to :author

class Paper < ActiveRecord::Base
  self.primary_key = 'pid'
  belongs_to :author, foreign_key: 'a_id'
end

在什么场合会用到

不知道这个例子 适合不?

class Category < ActiveRecord::Base
  belongs_to :parent, :foreign_key => :parent_id
  has_many :children, :foreign_key => :parent_id
end

谢谢 LS。我以为是belongs_to :author, foreign_key: 'aid', 其实应该是用foreign_key: 'a_id' 让我清楚了不少。

will_c_j 关于 Rails 外键的问题 提及了此话题。 08月10日 08:43
需要 登录 后方可回复, 如果你还没有账号请 注册新账号