How do I add a new element to an existing class? - ruby-on-rails

I already generated a class by "script/generate model blah blah1:string"
How would I add a "blah2:string" to the existing model? Is there a script or do I have to manually edit the database and every file?

Create migration:
./script/generate migration AddBlah2ToBlah blah2:string
This will create migration in db/migrate ruby file with migration - you can check if it correctly added column to table. Then run:
rake db:migrate
or in production environment:
rake db:migrate RAILS_ENV=production
This will add column to your database and you can use it in Rails:
#blah = Blah.first
#blah.blah2 = "new string"
...

You can create new migration of change table.. Check this.. See section 3.2

Related

Add and Change the default value for table column with migration

I currently have a migration and I simply want to add a couple more values to this migration such as to_limit and from_limit along with their default values (5&10). How should i do this?
class AddUserToCompany < ActiveRecord::Migration
def change
add_column :companies, :user, :jsonb, default: {"to_dist"=>50, "from_dist"=>70, "trs_one"=>100, "trs_two"=>120}
end
end
I added some changes which also requires "to_limit"=>5 and "from_limit"=>10. Please suggest on how to add a new migrate file and add the changes.
Rails version - 4.2.11
This is my first time working with a rails application. So i am really confused on how to proceed with this.
1.If this changes are in progress (not already used by other) then you can rollback this migration by command
rollback last migration
rake db:rollback STEP=1
In order to rollback ONLY ONE specific migration
rake db:migrate:down VERSION=20220905201547
and after applying changes, run rake db:migrate
If migration was created earlier then you can create new migration to apply your changes
generate new migration by command
rails generate migration nameOfMigration
I hope this helps

Rails: after using scaffold, I can't migrate

[rails 4.1.6, ruby 2.1.3p242 ]
1.set the database.yml database: bookshop , and created the bookshop database in my database.
2.create a new table books with id int(10), name varchar(45) by SQL( I use MySQL).
3.everything is Okay, I can open the project in the browser.
things became a little weird after I typed rails g scaffold Book id:integer name:string, which worked successfully.
But, as I restart the rails project, then the browser came out
"Migrations are pending. To resolve this issue, run: bin/rake db:migrate RAILS_ENV=development"
bin/rake db:migrate RAILS_ENV=development it shows
== 20141003105907 CreateBooks: migrating ======================================
-- create_table(:books)
rake aborted!
StandardError: An error has occurred, all later migrations canceled:
you can't redefine the primary key column 'id'. To define a custom primary key, pass { id: false } to create_table./usr/local/...
ID fields are added to models by default - you don't need to add them yourself.
Destroy the scaffold you made, with rails destroy scaffold Book, and create it again - this time without the id:integer field.

manually adding an integer field to rails scaffold

I'm new to rails...I made a scaffold "Reviews" but want to add another field "ratings", as an integer. I did the following:
added t.integer :ratings in the migration file..ran rake db:migrate
in spec folder: added it in views/app/ edit, index, new, show
in app/views/app added it in the json files
in app/controllers/app added it in the review_params function
still however whenever I try to reference (by showing a Review) it I get
undefined method `ratings' for #
There must be something else I need to add somewhere to have it be part of my Reviews scaffold. I've been trying to figure it out for 5 hours but still have not. When I try to remake a scaffold and run rake db:migrate I get an error saying that the databases already exist so I would like to just manually add it to my existing one if possible, I just can't seem to figure out how even though I've already done it once for a string.
Any help is appreciated thank you.
To add an integer field to a model you can do something like this.
rails generate migration AddRatingToReviews rating:integer
This should handle everything for you by generating a new migration file like so.
class AddRatingsToReviews < ActiveRecord::Migration
def change
add_column :reviews, :rating
end
end
Then you can run rake db:migrate to add the column to your review model.
NOTE: Before doing all of this, please delete all your manual changes. If necessary use rake db:rollback which will rollback your most recent rake db:migrate.
Recommendation
If you are new to rails and don't understand MVC, I suggest not using scaffolding because you'll have a tough time knowing what it is doing. Go through this awesome tutorial by Michael Hartl to really learn rails quickly. http://ruby.railstutorial.org/
*Awesome gem *
Use the annotate gem to display the attributes contained within your model directly in your name_of_model.rb files.
https://github.com/ctran/annotate_models
rails generate migration AddRatingsToReviews ratings:integer
Then
rake db:migrate
If you have not done any major changes in your generated scaffold.
Simplest way to get the ratings across views would be as below:
Rollback the changes that you have migrated
rake db:rollback VERSION=version_number
Where replace version_number with the version_number prefixed on your migration file.
For eg: If your migration filename is 20140314190622_create_reviews.rb then command should be
rake db:rollback VERSION=20140314190622
Destroy the scaffold of Review
rails d scaffold Review
After this generate the scaffold again with the integer field
rails g scaffold Review ratings:integer .... ## Add other field in place of ....

Rails destroy model not deleting migration

I originally had a migration called CreateUsers that had a table already.
Due to my stupidity, i thought i had to do a rails generate migration in order to add indexes to the table. When i did a migration it was this:
rails generate migration CreateUsers years:integer
So it creates a migration with the timestamp and so on, and i tried deleting using this
rails d migration migration_filename
Its giving me some error regarding this
/Users/giowong/.rvm/gems/ruby-2.0.0-p353/gems/activerecord-4.0.2/lib/rails/generators/active_record/migration/migration_generator.rb:57:in `validate_file_name!': Illegal name for migration file: 20140219230444_create_create_users.rb (ActiveRecord::IllegalMigrationNameError)
In the schema.rb table stll exists
should i manually delete both?
You don't want to run rails d against the filename, but against the migration name you had in your generate.
Try: rails d migration CreateUsers
In order to drop the table, you'll want to rollback your migration as well:
rake db:rollback STEP=1
STEP=1 assumes this was the last migration run. You also may need to prepend bundle exec if you're using bundler in your app.

Attempted to Recreate Rails model, migrations messed up

I had a rails Model List.
I typed rails d model list in my terminal, resulting in this:
invoke active_record
remove db/migrate/20140116161958_create__lists.rb
remove app/models/list.rb
invoke rspec
remove spec/models/list_spec.rb
Then I typed rails g model list name:string size:integer which gave me this:
invoke active_record
create db/migrate/20140213155321_create_lists.rb
create app/models/list.rb
invoke rspec
create spec/models/list_spec.rb
Now, running rake db:migrate gives me this:
== CreateLists: migrating ===============================================
-- create_table(:lists)
rake aborted!
An error has occurred, this and all later migrations canceled:
PG::DuplicateTable: ERROR: relation "lists" already exists
The issue is that my table was not deleted from my DB. I can't roll back the migration that created that table, because it was destroyed when i ran rails d model list.
I could create a new migration and drop the table, but it would be placed after my migration created when I ran rails g model list..., so I assume it would error too.
Is my only choice to delete the model again, create a migration to drop the table, then recreate the model?
Also, in the future, how should one go about deleting and recreating a model? Roll back the migration prior to rails d model?
1>
before running rails d model list
run
$ rake db:migrate:down VERSION=20140116161958
will roll back the list file to remove table lists from database.
2>
but since u have already destroyed your model what u can do is delete table lists from rails database console. try this
$ rails dbconsole # from your app root path
and then type drop table lists;
3>
you can drop your table from rails console also
$rails console
Then just type:
ActiveRecord::Migration.drop_table(:lists)
4>
also u can create a migration file to drop your table :
$ rails generate migration DropListsTable
this will create an empty migration file now edit that file to look like:
class DropListsTable < ActiveRecord::Migration
def up
drop_table :lists
end
def down
raise ActiveRecord::IrreversibleMigration
end
end
then run $ rake db:migrate

Resources