0

So i'm making a Rails application to learn how to use the framework.

I created a user using:

rails g model User name:string

Then I realized my user also needed another attribute and a relationship with another resource called user_role. Say my UserRole model is something like:

rails g model userRole roleName:string

So far I've found that I can only achieve the change using a migration, but this is rather inconvenient and unclear to me, since I don't really have any old data, I'm just adjusting my model.

Any advise for a noob?

tereško
  • 58,060
  • 25
  • 98
  • 150
LECHIP
  • 81
  • 1
  • 8

3 Answers3

0

Migration is extremely helpful. It keeps track of your schema changes. However, if you find that you forgot to add an field immediately after creating migration, you can edit the old migration without creating a new. If you already migrated your database (using rake db:migrate) you can rollback.

rake db:rollback

Now, edit the migration file and add/remove you fields. When completed, migrate again

rake db:migrate

When you create a separate model, you SHOULD create a separate migration. Otherwise, in future you will be confused yourself. btw, when creating children model, you don't need any change in the parent migration. you need to add foreign key in the child table. you can use something like this:

rails g model Comment post:references 

this will add post_id in the comment table.

HungryCoder
  • 7,506
  • 1
  • 38
  • 51
0

You could try a non-database backed ActiveModel-like model. For example, Mongoid or Datamapper. Many NoSQL solutions don't require migrations for changes to models.

Tsagadai
  • 887
  • 2
  • 8
  • 21
0

Try this:

rails g model ModelName --migration=false
pbms
  • 586
  • 1
  • 10
  • 32
  • Whilst this code snippet is welcome, and may provide some help, it would be [greatly improved if it included an explanation](//meta.stackexchange.com/q/114762) of *how* and *why* this solves the problem. Remember that you are answering the question for readers in the future, not just the person asking now! Please [edit] your answer to add explanation, and give an indication of what limitations and assumptions apply. – Toby Speight Mar 10 '17 at 11:17