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

标签 mysql ruby-on-rails ruby activerecord

我正在尝试使用 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/

相关文章:

Java异常空指针异常错误

php - fatal error : Unsupported operand types in .。?

ruby-on-rails - Ruby on Rails 和 Prawn PDF

ruby-on-rails - 如何在 Ruby on Rails 中启用压缩?

javascript - 使用 ExecJS 传递参数

php - Google Maps API v3 复选框/过滤器数据库

mysql - 如何在mysql中用新插入的值计算最后一行的值

ruby-on-rails - 删除 mongoid 中的嵌入文档

Ruby 和 JRuby 在同一台 Windows 7 计算机上

ruby-on-rails - Rails 以月为单位计算日期范围