表复数? [英] Table pluralization?

查看:70
本文介绍了表复数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 3 个具有以下关系的表(为了简单和清晰,对表进行了修剪):

I have 3 tables with the following relationships (tables have been trimmed for simplicity and clarity):

create_table "users", force: :cascade do |t|
  t.string "name", limit: 255, null: false
end

create_table "sleeves", force: :cascade do |t|
  t.integer "user_id", limit: 4
  t.integer "report_id", limit: 4
end

create_table "reports", force: :cascade do |t|
  t.string "name", limit: 255, null: false
end

我的模型是这样的:

class User < ActiveRecord::Base
  has_many :sleeves
end

class Sleeve < ActiveRecord::Base
  belongs_to :user
  has_many :reports
end

class Report < ActiveRecord::Base
  belongs_to :sleeve
end

但是,Rails 中的某种复数形式似乎存在问题.当我从控制台运行以下命令时:

However, there seems to be a problem with pluralization of some sort in Rails. When I run the following command from console:

user = User.find(1)
user.sleeves

我收到以下错误:

NameError: uninitialized constant User::Sleefe
from "../gems/ruby-2.2.2/gems/activemodel-4.2.3/lib/active_record/inheritance.rb:158:in 'compute_type'

如果我将模型中的用户关系更改为:

If I change the user relationship in the model to:

class User < ActiveRecord::Base
  has_one :sleeve
end

一切正常(但我只收到一份报告,而不是我需要的所有报告).我怀疑问题在于 Sleeve 一词的复数形式(正如错误所说的 Sleefe——它不在代码中的任何地方).

Everything works fine (but I only get one report and not the all the reports I need). I suspect the problem is with pluralization of the word Sleeve (as the errors says Sleefe -- which isn't anywhere in code).

谁能引导我走上正确的道路以进行更正?

Can anyone lead me down the right path for a correction?

推荐答案

复数形式被称为inflections" 在 Rails 中,它们是为您预定义的.

Plural forms are known as "inflections" in Rails, and they're predefined for you.

只是为了加深理解,Rails 使用了一堆正则表达式来根据单词的结尾方式来确定要使用的正确复数形式.(您可以在 your_application/lib/active_support/inflections.rb 中看到它们).正则表达式是一种匹配模式的有效方式,但它们依赖于目标材料的一致性.英语作为一种自然语言,不规则、不一致,sleefe"之类的问题就是这样产生的.

Just for the sake of deepening understanding, Rails uses a bunch of regular expressions to determine the proper pluralization to use based on the way the word ends. (you can see them in your_application/lib/active_support/inflections.rb). Regular expressions are an efficient way to match patterns, but they depend on consistency in the target material. English, as a natural language, is irregular and inconsistent, and this is how problems like "sleefe" arise.

在您的情况下,您希望通过对 Inflector 文件执行一些小手术来覆盖看起来不正确的变化.

In your case, you want to override what appears to be an incorrect inflection by performing some minor surgery on an Inflector file.

打开:

your_application/config/initializers/inflections.rb

编辑 inflections.rb 看起来像这样:

Edit inflections.rb to look something like this:

ActiveSupport::Inflector.inflections do |inflect|
  inflect.irregular 'sleeve', 'sleeves'
end

这篇关于表复数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆