在Rails ActiveRecord中访问和设置对象

one*_*nch 1 ruby mysql activerecord ruby-on-rails ruby-on-rails-3

我在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
Run Code Online (Sandbox Code Playgroud)

当我尝试调用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
Run Code Online (Sandbox Code Playgroud)

我的问题是为什么Rails试图通过foo的id选择bar,当我明显想要bar by foo的bar_id属性时.

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

Kir*_*rat 5

has_one关联外键放在referenced model(Bar)而不是declaring model(Foo).因此,在您的情况下,rails期望Bar模型中的外键为Bar.foo_id.这是错误消息中查询的原因.

您应该belongs_to在需要外键时declaring model使用,has_one如果您想在其他模型上使用它.

如果你想在Foo中使用foreign_key作为bar_id,那么,

你可以选择belongs_to :barIn Foo模型

要么

一个has_one :foo在Bar模型中.