【发布时间】:2013-12-04 13:21:19
【问题描述】:
我的一个 PG DB 表遇到了这个问题。我有一个表,其名称是“hproducts_rules”。这应该与“hproducts_matchs”表具有“belongs_to”关系。
这是我的表格架构:
hproducts_match
has_many :productsrule
default_scope order: 'id'
attr_accessible :productsrule_attributes, :product_id, :company_id, :product_key, :description, :condition
accepts_nested_attributes_for :productsrule, :reject_if => :all_blank, :allow_destroy => true
self.table_name = "hproducts_matchs"
hproducts_rule
belongs_to :productsmatch
default_scope order: 'id'
attr_accessible :productsmatch_id, :company_id, :product_key, :origen_comp, :line, :connector, :char_start, :char_end, :modeprize_id, code_opc, :ochar_start, :onchar_end self.table_name = "hproducts_rules"
当我尝试在“products_match”表单中添加部分内容时,我收到以下错误:
PG::UndefinedTable: ERROR: relation «productsrules» does not exists
LINE 5: WHERE a.attrelid = '"productsrules"'::regclas...
^
: SELECT a.attname, format_type(a.atttypid, a.atttypmod),
pg_get_expr(d.adbin, d.adrelid), a.attnotnull, a.atttypid, a.atttypmod
FROM pg_attribute a LEFT JOIN pg_attrdef d
ON a.attrelid = d.adrelid AND a.attnum = d.adnum
WHERE a.attrelid = '"productsrules"'::regclass
AND a.attnum > 0 AND NOT a.attisdropped
ORDER BY a.attnum
我最初以为是因为我的表名是“hproducts_match”,而我的“products_rules”表上的参考字段是“productsmatch_id”,所以我将名称更改为“hproductsmatch_id”并得到了相同的结果。然后我将整个表名更改为“products_rules”而不是“hproducts_rules”,并且仍然相同。我什至在表和模型上加了一个foreign_key约束,还是一样。
我不确定该关系是否应该命名为“hproductsrules”或“productsrules”,所以也许这就是问题所在。我在哪里可以改变它?
我做了一些研究,其中大部分与迁移有关。我没有在我的数据库开发中使用迁移,我手动添加了表,就像我对每个表所做的那样。其他是关于 rspec 的,超出了我的范围。
有人知道为什么会这样吗?这仅在我使用表单中的部分时才会显示。
提前致谢。
编辑以显示我的答案
好的,由于某种明显的原因,我的应用程序假设我的表名是“productsrules”而不是“hproducts_rules”,所以我所做的就是将“self.table_name”行更改为模型的顶部,然后一切正常.
不确定这是否是这个问题的正确答案,但它帮助我解决了这个问题。
我将我的模型恢复到原始状态(我在这个问题开始时有一个)唯一的区别如下:
class Productsrule < ActiveRecord::Base
self.table_name = "hproducts_rules"
belongs_to :productsmatch
default_scope order: 'id'
attr_accessible :productsmatch_id, :company_id, :product_key, :origen_comp, :line, :connector, :char_start, :char_end, :modeprize_id, code_opc, :ochar_start, :onchar_end
end
如您所见,self.table_name 行位于模型的开头。
感谢所有回复的人:)
【问题讨论】:
-
您自己创建了表,并且您正在重命名东西,那么为什么不使用 rails 默认命名呢?它会让你的生活更轻松,而且命名约定是明智和好的。
-
好吧,不一定是创建表的我,而是使用数据库的团队。但是,是的,你的建议很有道理,所以我以后会让他们知道。
标签: ruby-on-rails ruby activerecord rails-activerecord rails-postgresql