In Ruby on Rails, if I want to use the scaffold generator, can I use a field name with more than 1 word i.e
'class name':text
As opposed to just
name:text
I have tried looking and also tried but cannot figure out if this is possible.
Additionally, if I want to generate a scaffold which would be called Class, I appear to be unable to do this - but I would like my users to see the word 'class' rather than whatever new name I am going to have to pick. Anyway around this?
Sure:
rails g migration Foo "bar baz":string
rake db:migrate # => SyntaxError
Oops. That generates a migration like this:
class CreateFoos < ActiveRecord::Migration
def change
create_table :foos do |t|
t.string :bar baz
t.timestamps
end
end
end
Obviously that won't work. You can fix it by wrapping the symbol in quotes:
t.string :"bar baz"
Now the migration works, but can we use the model?
> f = Foo.new
> f.bar baz # nope
> f."bar baz" # nope
> f.send("bar baz") # Yay!
How to change the value?
> f.send("bar baz=", "wtf") # OK
> f.send("bar baz") # => "wtf"
So in a very narrow, technical sense, yes you can do this. But you shouldn't.
I would like my users to see the word 'class' rather than whatever new name I am going to have to pick
You can always use a different method (i.e., an alias) for user-facing code to display a column or model name. This can be as simple as defining your own method on a model, or using a helper function, or a decorator class. You definitely want to avoid using terms that Ruby and Rails use (like Class).