gpt4 book ai didi

mysql - 在 Rails ActiveRecord 中访问和设置对象

转载 作者:太空宇宙 更新时间:2023-11-03 17:23:32 25 4
gpt4 key购买 nike

我在 Rails 3.2 中有一个我们称之为 Foo 的类,它有另一个名为 Bar 的类(都是 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

我的问题是为什么 Rails 试图通过 foo 的 id 选择 bar 而我显然想要 bar by foo 的 bar_id 属性。

如果这需要更多解释,请告诉我。

最佳答案

has_one 关联外键放置在引用模型(Bar) 中而不是声明模型(Foo) 中。因此,在您的情况下,rails 期望 Bar 模型中的外键为 Bar.foo_id。这是错误信息中查询的原因。

当你想在声明模型中使用外键时,你应该使用belongs_to,如果你想在另一个模型中使用它,请使用has_one

如果你想要 Foo 中的 foreign_key 作为 bar_id 那么,

你可以选择 belongs_to :bar In Foo 模型

或者

Bar 模型中的 has_one :foo

关于mysql - 在 Rails ActiveRecord 中访问和设置对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21948450/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com