在 Ruby on Rails 中,脚手架字段名称可以包含多个单词吗

In Ruby on Rails can a scaffold field name contain more than one word

在 Ruby on Rails 中,如果我想使用脚手架生成器,我可以使用超过 1 个单词的字段名称吗,即

'class name':text

相对于

name:text

我试过也试过,但不知道这是否可行。


此外,如果我想生成一个名为 Class 的脚手架,我似乎无法做到这一点 - 但我希望我的用户看到 'class' 这个词而不是无论我将不得不选择什么新名字。不管怎样?

当然可以:

rails g migration Foo "bar baz":string

rake db:migrate # => SyntaxError

糟糕。生成这样的迁移:

class CreateFoos < ActiveRecord::Migration
  def change
    create_table :foos do |t|
      t.string :bar baz

      t.timestamps
    end
  end
end

显然这行不通。您可以通过将符号括在引号中来修复它:

t.string :"bar baz"

现在迁移成功了,但是我们可以使用模型吗?

> f = Foo.new
> f.bar baz # nope
> f."bar baz" # nope
> f.send("bar baz") # Yay!

如何修改值?

> f.send("bar baz=", "wtf") # OK
> f.send("bar baz") # => "wtf"

所以从非常狭隘的技术意义上讲,是的,你可以做到这一点。但你不应该。

I would like my users to see the word 'class' rather than whatever new name I am going to have to pick

您始终可以对面向用户的代码使用不同的方法(即别名)来显示列或模型名称。这可以像在模型上定义自己的方法一样简单,或者使用辅助函数或装饰器 class。您肯定要避免使用 Ruby 和 Rails 使用的术语(例如 Class)。