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

标签 mysql ruby-on-rails ruby ruby-on-rails-3 activerecord

我在 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/

相关文章:

ruby - 使用 JRuby 或 bundle exec 时如何使用 rspec 启用颜色?

mysql - 在 Ruby 中使用 Mysql gem 运行脚本(多个语句)

mysql - 导入的 csv 文件的列少于我要导入的表?

ruby-on-rails - rvm 与 sqlite3 冲突

javascript - 使用 php 无法将网络摄像头生成的图像上传到 mysql 数据库

ruby-on-rails - Rails jbuilder DateTime 将小数添加到秒

mysql - 加入 Rails 中的多个协会

ruby - 基于另一个下拉列表的选择的下拉列表

mysql - SQL 查询将我的自动增量列 ( id ) 设置为零或重置自动增量字段的值

php - 第二个提交按钮不像第一个那样工作