mysql - 通过ActiveRecord查询MySQL错误

标签 mysql ruby-on-rails ruby

我是 RoR 新手。我正在尝试查看我的 MySQL 连接是否设置正确。 我的 Controller 中有以下代码:

require 'rubygems' # Only if installed via RubyGems

class HomeController < ApplicationController
  User.find(1)

  def index
  end
end

这在我的 user.rb 类中:

class User < ActiveRecord::Base
end

显然我在 MySQL 中有一个用户表。

我收到这样的错误:

undefined method `eq' for nil:NilClass

知道为什么吗?另外,如何将查询代码从 Controller 中取出并放入模型类型的文件中?

最佳答案

我认为你的代码应该看起来更像这样:

class HomeController < ApplicationController
  def index
    @user = User.find(1)
  end
end

当使用基本查找等时,您应该在 Controller - ofc 中查询您的模型。

在更复杂的情况下,您应该使用范围: http://asciicasts.com/episodes/202-active-record-queries-in-rails-3

关于mysql - 通过ActiveRecord查询MySQL错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5863475/

相关文章:

php - 在应用程序的页脚中写入 git commit 版本信息

mysql - 如何在rails项目中从sqlite3迁移到mysql?

ruby-on-rails - 重新分配路线的最佳方法是什么

ruby - 是否有针对 Ruby 的 ISO-8601 日期解析的完整实现?

ruby-on-rails - 覆盖 RSpec 生成器模板

mysql - 根据行在表中的位置删除行

mysql - 添加第四个表连接时结果减少

mysql - 使用 !empty 旧行列填充空数据库列

ruby-on-rails - mongodb:获取特定文档然后获取其余文档的最佳方式

ruby-on-rails - 如何打印 :text? 中的确切字符数