ruby-on-rails - ActiveRecord 如何找到模型的属性?

标签 ruby-on-rails ruby ruby-on-rails-3

这是我的问题。

我想知道 active record 如何访问数据库中的表和列?

最佳答案

回答您问题的大部分代码都包含在 model_schema.rb 中文件。

table_name 是与您的模型对应的数据库表的名称。如文档中所述,除非明确设置,否则根据模型名称进行猜测。

Guesses the table name (in forced lower-case) based on the name of the class in the inheritance hierarchy descending directly from ActiveRecord::Base. So if the hierarchy looks like: Reply < Message < ActiveRecord::Base, then Message is used to guess the table name even when called on Reply. The rules used to do the guess are handled by the Inflector class in Active Support, which knows almost all common English inflections. You can add new inflections in config/initializers/inflections.rb.

Nested classes are given table names prefixed by the singular form of the parent's table name. Enclosing modules are not considered. You can also set your own table name explicitly:

class Mouse < ActiveRecord::Base
  self.table_name = "mice"
end

Alternatively, you can override the table_name method to define your own computation. (Possibly using super to manipulate the default table name.) Example:

class Post < ActiveRecord::Base
  def self.table_name
    "special_" + super
  end
end

对于列,它有点复杂。你可以从 columns 开始从 schema.rb 中获取列定义的方法文件并返回它们。

列在 schema.rb 中明确定义应用程序中的文件。

关于ruby-on-rails - ActiveRecord 如何找到模型的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20701581/

相关文章:

css - Bootstrap Rails - 更改背景颜色,不起作用?

ruby-on-rails - Windows 上的 Ruby On Rails 与 Mongrel

mysql - 为 RoR 设置 MySQL 数据库时出错

ruby-on-rails - 将 `acts_as_list` 添加到 gemfile,rails 在运行 rails s 时给出错误 :`bundler: failed to load command: rails`

ruby-on-rails - ruby 中的 Postgres 数据类型整数 []

ruby - 如何获取 ActiveRecord 3.x 中的所有范围列表

ruby-on-rails - 从使用回形针上传的原始图像中删除 exif

jquery - 如何为 jQuery 实现标签插件

ruby 模式问题

用于匹配 url 的 Ruby 正则表达式