将自定义外键分配给Rails Junction表

时间:2015-09-05 00:08:52

标签: mysql ruby-on-rails ruby model foreign-keys

我有一个数据库,其中许多“帖子”可以包含许多“标签”。我在帖子和标签之间设置了一个名为'post_tag'的联结表 但是,帖子和标签的外键列的名称在post_tag中是不同的。

这就是我在post_tag模型中所拥有的:

class PostTag < ActiveRecord::Base
  self.table_name = "post_tag"

  #defining columns in post_tag that are foreign keys for post and tag tables
  belongs_to :post, :class_name => "Post", :foreign_key => "post_fk"
  belongs_to :tag, :class_name => "Tag", :foreign_key => "tag_fk"
end

:foreign_key是post_tag联结表中外键列的名称。在post_tag中,这些外键字段等于post或tag表中的主键。 这是我得到的错误:

irb(main):001:0> p = post.find(1)
irb(main):002:0> p.post_tags
      PostTag Load (0.9ms)  SELECT `post_tag`.* FROM `post_tag` WHERE `post_tag`.`post_id` = 1
    Mysql2::Error: Unknown column 'post_tag.post_id' in 'where clause': SELECT `post_tag`.* FROM `post_tag` WHERE `post_tag`.`post_id` = 1
    ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'post_tag.post_id' in 'where clause': SELECT `post_tag`.* FROM `post_tag` WHERE `post_tag`.`post_id` = 1

如何让它停止寻找post_idpost_fk

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

事实证明:foreign_key => "actual_foreign_key"已弃用。

应改为使用foreign_key: "actual_foreign_key"