gpt4 book ai didi

mysql - ActiveRecord Many_to_many 具有自定义表和列名称

转载 作者:行者123 更新时间:2023-11-29 13:15:53 26 4
gpt4 key购买 nike

我正在尝试使用 ActiveRecord 在 Sinatra 中映射我的 MySQL dB。该数据库不遵循 ActiveRecord 约定,因此我需要将添加属性的所有内容映射到我的类。

一对多和一对一关联一切正常,但 m 到 m 关联有问题。

我有一个名为“Eve_Articles”的文章表

我有一个名为“Eve_product”的产品平板电脑

我有一个名为“Eve_Articles_Product”的联接表,其中 tree_id 是文章 ID,prod_id 是产品 ID。

我创建模型:

class Article < ActiveRecord::Base
self.inheritance_column = :_type_disabled
has_one :image, class_name: 'Image', foreign_key: 'tree_id'
has_and_belongs_to_many :products,

end

class Product< ActiveRecord::Base
self.inheritance_column = :_type_disabled
has_and_belongs_to_many :articles,
end

但我不知道如何使用自定义键定义自定义联接表。

最佳答案

使用join_table选项。此外,您还必须为 ArticleProduct 设置 table_name,因为它不遵循 Rails 约定

您必须根据文档中的这一行在 habtm 调用后设置表名称。

WARNING: If you’re overwriting the table name of either class, the table_name method MUST be declared underneath any has_and_belongs_to_many declaration in order to work.

class Article < ActiveRecord::Base 
self.inheritance_column = :_type_disabled
has_one :image, class_name: 'Image', foreign_key: 'tree_id'
has_and_belongs_to_many :products, :join_table => "Eve_Articles_Product", :association_foreign_key => 'tree_id', :foreign_key => 'prod_id'
self.table_name = "Eve_Products"
end

class Product< ActiveRecord::Base
self.inheritance_column = :_type_disabled
has_and_belongs_to_many :articles, :join_table => "Eve_Articles_Product", :association_foreign_key => "prod_id", :foreign_key => 'tree_id'
self.table_name = "Eve_Articles"
end

关于mysql - ActiveRecord Many_to_many 具有自定义表和列名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21461305/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com