我使用Rails 2.3.14如果model在深名稱空間中,set_table_name不起作用 - 在rails 2.3.14中的錯誤?
更新3我在更新2中招只適用於該協會的第一次訪問......所以,我堅持我的應用程序控制器的set_table_name線。這太奇怪了。我希望這得到修復。 = \
UPDATE 2如果我手動/ nastily/hackily爲環境文件底部的麻煩類別設置表格,我不會收到錯誤。
應用程序/配置/ environment.rb中:
Page::Template::Content.set_table_name "template_page_contents"
Page::Template::Section.set_table_name "template_page_sections"
爲什麼我必須這樣做?對於這個特殊的用例,軌道是否被打破?
UPDATE:看起來set_table_name在我的Page :: Template :: Content類中最初被調用時不起作用。
,但如果我把它之前,我使用的關聯,它的工作原理...
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
通過has_many
關係屬於Page::Template
。
Mysql2::Error: Unknown column 'contents.template_page_id' in 'where clause': SELECT * FROM `contents` WHERE (`contents`.template_page_id = 17) LIMIT 1
望着錯誤日誌,我想我需要使用一些打印語句,找出原因軌試圖找到錯誤的表關聯的對象開始。
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"
應用程序/模型/頁/ 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
那麼......是什麼原因造成這一點,我該如何解決?
這是很透徹!謝謝! = d – NullVoxPopuli 2012-08-12 18:13:21