如何使用 :through 选项声明 has_many 关联的特定键?

发布于 2024-09-14 04:22:38 字数 603 浏览 9 评论 0原文

我有一个协会:
一个作者有很多本书; 一本书有很多作者;
我需要使用 :through 选项(通过名为“关系”的表,有两列名为“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' 这样的选项吗?)

I have an association:
an author has many books;
and a book has many authors;
I need to use :through option(through a table named 'relations',has two column named 'left_id' (used as author_id) and 'right_id' (used ad 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

In the console:


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

So, how could I specific the 'book_id' to 'right_id'?(Is there some option like 'foreign_key'?)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

命硬 2024-09-21 04:22:38

您还应该在关系模型中使用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

You should use a foreign_key also in the Relation model, so the belongs_to has also foreign_key. More specifically this is what you need:

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

and the other models should be:

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
原来是傀儡 2024-09-21 04:22:38

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

has_many :relations, :local_key => 'left_id', :foreign_key => 'right_id'

I don't know about foreign_id and can't find anything on google. How about this?

has_many :relations, :local_key => 'left_id', :foreign_key => 'right_id'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文