我正在使用 Rails 2.3.14
更新 3我在更新 2 中发现的技巧仅适用于关联的第一次访问......所以,我将 set_table_name 行粘贴在我的应用程序控制器中。这太奇怪了。我希望这得到修复。=\
更新 2如果我手动 / 讨厌 / hackily 为环境文件底部的麻烦类设置表格,我将停止收到错误。
应用程序/配置/环境.rb:
Page::Template::Content.set_table_name "template_page_contents"
Page::Template::Section.set_table_name "template_page_sections"
为什么我必须这样做?对于这个特定的用例,rails 是否损坏?
更新:在我的 Page::Template::Content 类中最初调用 set_table_name 时,它似乎不起作用。
但如果我在使用关联之前调用它,它会起作用......
ap Page::Template::Content.table_name # prints "contents"
Page::Template::Content.set_table_name "template_page_contents"
ap Page::Template::Content.table_name # prints "template_page_contents"
return self.page_template_contents.first # doesn't error after the above is exec'd
原始问题:
TL; DR:我尝试访问一个 has_many 关系,但 Rails 认为 has_many 关系使用的表是不同的表
我一直收到此错误,当我尝试通过关系访问Page::Template::Content
that belongs_to a时。Page::Template
has_many
Mysql2::Error: Unknown column 'contents.template_page_id' in 'where clause': SELECT * FROM `contents` WHERE (`contents`.template_page_id = 17) LIMIT 1
查看错误日志,我想我需要开始使用一些打印语句来找出为什么 rails 试图在错误的表中找到关联的对象。
gems_path/activerecord-2.3.14/lib/active_record/associations/association_collection.rb:63:in `find'
我只是决定打印该@reflection
对象,因为一切似乎都在发生。我是这样做的:
require "awesome_print" # best console printer (colors, pretty print, etc)
def find(*args) # preexisting method header
ap "-------" # separator so I know when one reflection begins / ends, etc
ap @reflection # object in question
... # rest of the method
在错误之前打印的最后一个“@reflection”:
"-------"
#<ActiveRecord::Reflection::AssociationReflection:0x108d028a8
@collection = true,
attr_reader :active_record = class Page::Template < LibraryItem {...},
attr_reader :class_name = "Page::Template::Content",
attr_reader :klass = class Content < LibraryItem {...},
attr_reader :macro = :has_many,
attr_reader :name = :page_template_contents,
attr_reader :options = {
:foreign_key => "template_page_id",
:class_name => "Page::Template::Content",
:extend => []
},
attr_reader :primary_key_name = "template_page_id",
attr_reader :quoted_table_name = "`contents`"
>
上面的代码块有几处错误。
:klass should be Page::Template::Content
:name should be :contents
:quoted_table_name should be `contents`
我的模型是如何设置的:
应用程序/模型/page.rb:
class Page < LibrayItem
belongs_to :template_page, :class_name => "Page::Template"
应用程序/模型/页面/模板.rb
class Page::Template < Library Item
set_table_name "template_pages"
has_many :page_template_contents,
:class_name => "Page::Template::Content",
:foreign_key => "template_page_id"
应用程序/模型/页面/模板/内容.rb
class Page::Template::Content
set_table_name "template_page_contents"
belongs_to :template_page,
:class_name => "Page::Template",
:foreign_key => "template_page_id"
class Page::Template
...
return self.page_template_contents.first
关联选择的类(与我上面的页面/模板结构无关):
class Content < LibraryItem
set_table_name "contents"
# no associations to above classes
那么...是什么原因造成的,我该如何解决?