【问题标题】:Rails 4 ActiveRecord has many through relationship not working from sql file readRails 4 ActiveRecord 有很多通过关系不能从 sql 文件读取
【发布时间】:2016-04-18 23:39:54
【问题描述】:

我目前正在从事一个项目,我必须从现有的 .sql 文件中填充 postgresql 数据库,然后使用 ActiveRecord::Base.connection.execute(IO.read("path/to/file.sql")) 为数据库播种

这会创建许多表和连接表,它们没有关联的迁移。

当我创建与数据库一起使用的 ActiveRecord 模型时,一切顺利,直到我尝试通过几个(预先存在的)连接表建立关系。 示例:

class Store < ActiveRecord::Base
   has_many :stores_teas
   has_many :teas, through: :stores_teas
end

class Tea < ActiveRecord::Base
  has_many :stores_teas
  has_many :stores, through: :stores_teas
end

class StoresTeas < ActiveRecord::Base
  belongs_to :store
  belongs_to :tea
end

当我尝试拨打 store.teas 之类的电话时,我收到一个错误:

NameError: uninitialized constant Store::StoresTea
from .../.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.3/lib/active_record/inheritance.rb:158:in `compute_type'

我之前在其他项目中多次设置过这样的关系,但我总是通过 rails 迁移创建表,而不是从同样创建表的 sql 文件中加载。我还需要做什么来映射关系?

【问题讨论】:

  • app/models中有嵌套文件夹吗?这些类的表中是否有一个名为 type 的列?
  • 除了生成的concerns文件夹之外,没有。
  • 没有“类型”列?
  • 不,任何表格中都没有类型列

标签: sql postgresql ruby-on-rails-4 activerecord


【解决方案1】:

您对 foreign_keys 和 ActiveRecord 关联感到困惑。

class StoresTeas < ActiveRecord::Base
  belongs_to :store
  belongs_to :tea
end

【讨论】:

  • 谢谢,为此...抱歉,这是一个错字。我会在问题中更改它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多