Re rake after you edit a model? - ruby

I am just starting my first ruby project. I followed tutorial and built a blog. I thought next i would add a commenting system to extend the project, I just added has_many :comments to my post model. In the tutorial after we built the model we raked the database. Im not entirely sure what it does, but it seems fairly important. Is this something at I will need to do again and any time i update a model? I am using the gem 'sqlite3'
thanks

Every time you create a new model (database table) you got to run the migration, which creates the table in the database. Whenever you make any change to the db, you got to run migrations so as to make sure your db is in sync with your latest changes.

Everytime, you create/edit a model(database table) in rails, you should write a migration for the same. The migration will make the necessary changes to your database once it is run using "rake db:migrate" command.
With the has_many :comments in your blog model. You will need to add a migration to create the comments table, with blog_id as the foreign key, assuming your blog model is called 'blog'.

Related

Migration to create table which is already present in database

I have created psql table through psql console. I have created a model in rails for the corresponding table. Now if I want to write a migration to create a table so that someone using my code doesn't need to create a table through psq console, and also it should not remove table for me when running the migration. How to solve this.
In your migration file:
create_table :foo do
.....
end unless table_exists? :foo
ActiveRecord::ConnectionAdapters::SchemaStatements#table_exists?.
In case you are reading this answer, and you are on Rails 6, a new flag was added to #create_table in Rails 6 beta1 to address this exact problem.
Example:
create_table :posts, if_not_exists: true do |t|
t.string :title
end
Rails encourages developers to modify their database only through migration files. Because when you do manual changes, schema.rb is not updated. This will make other developers schema inconsistent with yours.
If you have created a table in your local database manually, you can drop the table manually and create a new migration file. Then if you run the migration file, it will create the table and update schema.rb accordingly.
If you still want to write the migration only for the other developers, you can create a migration with the create table and then comment it while running the migration. schema.rb will now be updated with the new table because Rails automatically tries to sync your database with the schema.rb file everytime you run a DB command. Now, uncomment the migration change and push your changes for other developers to get the table.

Add columns to a table managed by Sequel Model

I'm using Sequel::Model. My model has a set_schema block and a create_table call, so the database is completely managed by the model. The database is sqlite.
I'm trying to add columns to the database and I can't find a way to. Adding fields to the schema has no effect. Adding a migration or an alter_table call doesn't do anything. I've asked on IRC and read the docs. I can't find an example of anyone doing this, but it seems simple.
How do I add a column/field to a Sequel Model?
I did a bunch of research and talked to Jeremy Evans. I was going about this wrong. The right way to do this was to remove my schema plugin code and create_table block and move to using migrations. The steps I went through were:
Remove the schema code (create_table, set_schema) from my modesl
Dump the schema from my current sqlite data files into initial migrations into migration files via the sequel -d command
Create a new migration that adds the columns I need via add_column calls in an alter_table block in a change block
Apply the migrations via the sequel -m command
Create rake tasks to run the migrations and hook those tasks into my deploy tasks

Rails table doesn't exist after create model from existing table

I had an existing table named boss_name and I would like to create a rails model for it.
I used "rails generate bossname" to created the model and added the
self.table_name = "boss_name"
inside the class.
After the model had been successfully generated, I tried to start up rails console and trying to query the table.
Bossname.first give me the first value from boss_name table without problem.
rails console worked fine but when I'm running rspec for bossname_spec.rb, I had error which say "Bossname(Table doesn't exist)".
I hope anyone can tell me why it work for rails console and doesn't work for the application. Any hint on how to make it work on the application too is really appreciated.
That indicates that the boss_name table exists in your development database, but not in your test database. You can copy your current development database schema into your test database like this:
rake db:schema:dump
RAILS_ENV=test rake db:setup

How to add migration details to its corresponding model in Rails 4

I remember one of my colleagues did this but I don't remember how. Guess he used some gem or a rake task to achieve this.
Please share if you know how to do this.
Maybe even a gem that can add relevant associations automatically to the model file. This when we do rails g model.
You can use this gem:
https://github.com/ctran/annotate_models
Then run annotate from the terminal. It notes if the field is hstore or array type in case of postgresql. So it is very intelligent. Even myself made a commit to it ;)

Ruby: how to uninstall Devise?

I have installed Devise and now want to remove it, including all the files it has generated. How do I do that?
I'm looking at solving the same problem today and since this is not answered, giving it a go =)
Models
Devise generates a User model if you installed by default.
Remove the lines under devise. This is how mine looks like.
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
In attr_accessible, you may remove email, :password, password_confirmation and remember_me if you no longer need them.
Views
A default Devise install doesn't generate views in your app folder. If you generated overriding views for Devise, you may remove them by running rails destroy devise:views (Rails 3).
Generally, all the views are stored in app/views/devise.
Controllers
By default, Devise doesn't generate any controllers too. If you did any overrides, they are most likely known as registrations_controller. Search your project for controllers that inherit Devise::RegistrationsController class.
Also, if you followed Devise's wiki and monkey-ed around to add redirect methods etc, look out for methods such as after_sign_in_path_for, store_location etc that are for redirecting users.
Migrations
If you installed Devise via its generators, look out for a migration create_users. If you don't need it anymore, use drop_table :users in a migration to get rid of it.
I'll assume most people would want to keep their User model. If you're using Devise < 2.0, the migrations are done by helpers. Once you remove Devise from the Gemfile, Rails will not understand the helpers below and throw errors, for instance, when you're trying to rerun these migrations on another box. These helpers are:
t.database_authenticatable
t.recoverable
t.rememberable
t.trackable
t.encryptable
t.confirmable
t.lockable
t.token_authenticatable # => becomes t.string :authentication_token
For the exact columns, the below is reference to the columns generated by Devise.
https://github.com/plataformatec/devise/wiki/How-To:-Upgrade-to-Devise-2.0-migration-schema-style
The guide above lists the fields generated by Devise using the helpers. You should be able to look through the list and your model (e.g. calling User in console), generate a migration that removes those columns.
BUT...
It's a little unfortunate that for consistency, we have to convert the migration to not use helpers using the guide above then generate a migration to remove them. This is for migration history consistency, otherwise anyone running the migrations might try to call the non-existent helpers. Also, your migration to remove the fields will also expect the fields to be present.
Alternatively, it might be a good time to squash the migrations and rely on schema.rb / structure.sql for the schema's to-date state. Even after deleting migrations, you can always recreate your development DB anytime using rake db:schema:load.
Initializers and Locale
Remove devise.rb in config/initializers and devise.en.yml in config/locales.
Routes
Remove any devise_for lines. These will raise errors after the removal of the gem.
Gem File
Yaay. All dome, remove the line gem 'devise' from your gemfile.
Use the generator to remove configuration files as well (step 2), so the whole process would be (referencing previous answers):
Remove the table: rake db:rollback VERSION=<insert the version number of the migration>
Remove the configuration: rails destroy devise:install
Remove your User model: rails destroy devise User (replace 'User' with the name of your model)
Remove references to devise in your routes.rb, gemfile, controller files, and view files like the following, if you used them (once again replacing 'user' with your model name):
devise_for (routes.rb)
gem 'devise' (gemfile)
before_action :authenticate_user! (controllers)
user_signed_in? (controllers, views)
current_user (controllers, views)
user_session (controllers, views)
In my case I had two models User and Admin and I am sticking with Devise, but I had a name collision issue with ActiveAdmin that requires me to remove the Admin model. But because there were so many references to Admin in devise, I had to take the steps below. I think it answers the original question above as well, though. I believe the correct way to do this is:
1.Find the devise migration for the user model and roll it back [IMPORTANT: IF you DON'T want to remove the user table associated with Devise, then SKIP THIS STEP]:
rake db:rollback VERSION=<insert the version number of the migration>
example:
rake db:rollback VERSION:20110430031806
2.Run this command to remove Devise and associated files.
rails destroy devise Admin (if Admin is the name of the model with user accounts).
This produces this output:
invoke active_record
remove db/migrate/20110430031806_devise_create_admins.rb
remove app/models/admin.rb
invoke test_unit
remove test/unit/admin_test.rb
remove test/fixtures/admins.yml
route devise_for :admins
3.To completely remove Devise, you need to remove all references to it in your models, controllers and views. This is manual work. The answer above provides good details for finding this cruft, but was incomplete for my purposes. I hope this helps someone else.
I found daemonsy's reply to be very helpful. Here are a few other things to consider as you do this.
Replacing Devise
If you are going to replace Devise with your own authentication, I recommend this Railscast: Authentication from Scratch (revised) (subscription required, but it's the best $9/mo you can spend).
And this Railscast (no subscription required) can help with a forgot password link and "remember me" option (things Devise offers out of the box, but that you can build pretty easily yourself): Remember Me & Reset Password
Tests
Before you do this, I recommend running all your tests to make sure they're passing.
After you remove Devise, your authentication-dependent tests will probably fail, so plan to spend some time fixing failing tests. This is a good thing because it will help you see what stuff "broke" when you removed Devise.
Make sure you check your test helpers as well. Most of my helpers were in /spec/spec_helper.rb. In fact, most of my failing tests began passing once I updated the methods in spec_helper.rb (eg, "login_user").
This worked for me!
1: rails d devise User This deletes the model and the routes.
2: rails d devise:install , This destroys devise.rb and
devise.en.yml files.
3: create a migration eg: rails g migration drop_user_table. I
used drop_table :users , force: :cascade, force: :cascade; takes
care of
PG::DependentObjectsStillExist: ERROR:
that occurs if other tables depend on the user table.

Resources