Ruby/Rails - 用两个词命名的模型(命名约定问题)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4893342/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ruby/Rails - Models Named with Two Words (Naming Convention Issues)
提问by ChrisWesAllen
This is really a question about naming conventions.
这实际上是一个关于命名约定的问题。
I have a model called PromotedEvents
我有一个模型叫做PromotedEvents
The file is called promoted_events.rb
该文件名为promoted_events.rb
I created the table with:
我创建了表:
create_table :promoted_events do |t|
Now I'm having problems creating anything, so I'm wondering if theres some problem using model with two words
现在我在创建任何东西时都遇到了问题,所以我想知道使用带有两个词的模型是否有问题
im in the console and tried
我在控制台中并尝试过
a = PromotedEvents.new
a = Promoted_Event.new
a = promoted_event.new
and keep getting a nameerror : uninitialized constanterror
并不断nameerror : uninitialized constant出错
Any ideas?
有任何想法吗?
回答by Alex Wayne
Your class should be singlular.
你的班级应该是单一的。
Name it PromotedEventin the file promoted_event.rb
PromotedEvent在文件中命名promoted_event.rb
a = PromotedEvent.new
回答by loosecannon
Model names are singular and camel case like so pe = PromotedEvent.new()
型号名称是单数和驼峰式的 pe = PromotedEvent.new()
the file should be promoted_event.rb
该文件应该是 promoted_event.rb
Controllers are plural
控制器是复数
PromotedEventsController
PromotedEventsController
constants are ALL_CAPS
常数是 ALL_CAPS
locals are separated_by_underscores_and_lowercase
当地人是 separated_by_underscores_and_lowercase
table names are plural 'SELECT * FROM promoted_events`
表名是复数 'SELECT * FROM Promotion_events`
回答by markquezada
If it helps, I always think of it like this:
如果有帮助,我总是这样想:
The model name is singular because it represents a single, specificthing. So, PromotedEventis a specific promoted event that has a name, date, etc.
模型名称是单数,因为它代表一个单一的、特定的事物。因此,PromotedEvent是具有名称、日期等的特定促销事件。
The table name on the other hand is plural. This is because the table stores a collectionof these singular items. So, promoted_events.
另一方面,表名是复数。这是因为该表存储了这些单一项目的集合。所以,promotion_events。
In rails, filenames are mostly a matter of convention since ruby has pretty lax rules in this regard, but generally it's class_name.rb. This pagemight help you get a better overview of what conventions are used where and what is specific to Ruby versus Rails.
在 rails 中,文件名主要是一个约定问题,因为 ruby 在这方面有相当宽松的规则,但通常它是class_name.rb. 此页面可能会帮助您更好地了解 Ruby 与 Rails 之间使用的约定以及特定于哪些约定。
回答by Danny
If you are an extreme rails n00b like me, then you will want to remember to create a class definition for your newly created table and place it in app/models.
如果你和我一样是一个极端的 rails n00b,那么你会想要记住为你新创建的表创建一个类定义并将它放在 app/models 中。
It would go like
它会像
class LargeCat < ActiveRecord::Base
belongs_to :zoo
end

