将自定义外键分配给 Rails 结点 table
Assigning custom foreign keys to Rails Junction table
我有一个数据库,其中很多 'posts' 可以有很多 'tags'。我在 post 和名为 'post_tag' 的标签之间设置了一个连接点 table
但是 post 的外键和标签的列名在 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结table.Inpost_tag中外键列的名称post_tag这些外键字段等于[=35=中的主键] 或标记 table。
这是我得到的错误:
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_id
而寻找 post_fk
?
感谢您的帮助!
原来 :foreign_key => "actual_foreign_key"
已贬值。
应该改用foreign_key: "actual_foreign_key"
!
我有一个数据库,其中很多 'posts' 可以有很多 'tags'。我在 post 和名为 'post_tag' 的标签之间设置了一个连接点 table 但是 post 的外键和标签的列名在 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结table.Inpost_tag中外键列的名称post_tag这些外键字段等于[=35=中的主键] 或标记 table。
这是我得到的错误:
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_id
而寻找 post_fk
?
感谢您的帮助!
原来 :foreign_key => "actual_foreign_key"
已贬值。
应该改用foreign_key: "actual_foreign_key"
!