![](/img/trans.png)
[英]Save Rails ActiveRecord objects into a temporary table (MySQL)
[英]Accessing and setting objects in Rails ActiveRecord
我在Rails 3.2中有一個類,我們將Foo稱為另一個名為Bar的has_one的類(均為ActiveRecords),如下所示:
class Bar < ActiveRecord::Base
attr_accessible :name
end
class Foo < ActiveRecord::Base
has_one :bar
def bar_name
if bar
bar.name
else
nil
end
end
當我嘗試調用bar_name時,出現如下所示的mysql錯誤:
ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'bar.foo_id' in
'where clause': SELECT `bar`.* FROM `bar` WHERE `bar`.`foo_id` = 1 LIMIT 1
我的問題是為什么當我明確想要bar_id的foo屬性的bar時,Rails試圖選擇foo的id的bar。
請讓我知道是否需要更多說明。
通過has_one
關聯,將外鍵放置在referenced model(Bar)
而不是在declaring model(Foo)
。 因此,在您的情況下,Rails期望Bar
模型中的外鍵為Bar.foo_id
。 這是在錯誤消息中進行查詢的原因。
如果要在declaring model
中使用外鍵,則應使用belongs_to
;如果要在其他模型上使用它,則應使用has_one
。
如果您希望Foo中的Foreign_key作為bar_id,
您可以在Foo模型中使用一個belongs_to :bar
要么
Bar模型中的has_one :foo
。
看來您的關系倒退了。 在您的情況下, class Foo
應該具有屬belongs_to :bar
而不是has_one :bar
。
class Foo < ActiveRecord::Base
belongs_to :bar
...
end
具有另一個表的鍵的關系中的表在關聯中始終使用belongs_to
。 有關belongs_to
關聯(以及通常的關聯)的更多信息,請參見:
http://guides.rubyonrails.org/association_basics.html#the-belongs-to-association
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.