我的一个 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 命名约定时,您必须显式指定外键和类名。与显式设置表名称的方式类似
hproducts_match
has_many :products_rules, :foreign_key => "productsmatch_id", :class_name => "HproductsRule"
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 :products_match, :foreign_key => "productsmatch_id", :class_name => "HproductsMatch"
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"
关于ruby-on-rails - PG::UndefinedTable:错误:关系“productsrules”不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20376520/