2

我有一个联想:
一个作者有很多书;一本书有很多作者;
我需要使用:通过选项(通过一个名为“关系”的表,有两列名为“left_id”(用作author_id)和“right_id”(用于广告book_id);


class Relation < ActiveRecord::Base
  belongs_to :books
  belongs_to :authors
end

class Author < ActiveRecord::Base
  has_many :relations, :foreign_key => 'left_id'
  has_many :books, :through => :relations
end

在控制台中:


> author = Author.new
> author.books 
#  => Error: no such column: relations.book_id

那么,我如何将 'book_id' 指定为 'right_id'?(有没有像 'foreign_key' 这样的选项?)

4

2 回答 2

0

您也应该在关系模型中使用 foreign_key,因此 belongs_to 也有 foreign_key。更具体地说,这是您需要的:

class Relation < ActiveRecord::Base
  belongs_to :book, :foreign_key => :left_id
  belongs_to :author, :foreign_key => :right_id
end

其他模型应该是:

class Book < ActiveRecord::Base
  has_many :relations, :foreign_key => :left_id
  has_many :authors, :through => :relations
end


class Author < ActiveRecord::Base
  has_many :relations, :foreign_key => :right_id
  has_many :books, :through => :relations
end
于 2010-08-14T09:51:22.577 回答
-1

我不知道foreign_id,在谷歌上找不到任何东西。这个怎么样?

has_many :relations, :local_key => 'left_id', :foreign_key => 'right_id'
于 2010-08-14T07:21:47.590 回答