Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails console database schema checking

I'm new to rails/ruby and I was wondering how I can double check if my database schema is correctly built in rails console

In rails c

ActiveRecord::Base.connection.tables gave me the output of

["schema_migrations", "users", "expense_pictures", "income_pictures", "income_texts", "expense_texts"] 

How can I check within the console that I have the following schema correctly built?

enter image description here

From user to IncomePictures and ExpensePictures are foreign keys. IncomePictures to ExpensePictures are also foreign keys to their appropriate texts

Here are my models:

class ExpensePicture < ActiveRecord::Base

  belongs_to :user
  mount_uploader :image, ImageUploader
  has_one :expense_text
end

class ExpenseText < ActiveRecord::Base
  belongs_to :expense_pictures
end

class IncomePicture < ActiveRecord::Base
  belongs_to :user
  mount_uploader :image, ImageUploader
  has_one :income_text
end

class IncomeText < ActiveRecord::Base
  belongs_to :income_pictures
end

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :rememberable, :validatable

  has_many :expense_pictures 
  has_many :income_pictures

end
like image 538
Liondancer Avatar asked Jul 22 '14 07:07

Liondancer


People also ask

How do I view a database in Rails?

You can use rails dbconsole to view the database that your rails application is using. It's alternative answer rails db . Both commands will direct you the command line interface and will allow you to use that database query syntax.

What is database schema in rails?

It is used by the tests to populate the database schema. As such a rake db:schema:dump is often run as part of the rake test:prepare run. The purpose is that the schema of the test database exactly matches the current development database.


1 Answers

You can check this in db/schema.rb file. If you aren't sure, you can run bundle exec rake db:schema:dump previously - this rake task recreates schema.rb file from database.

According to your edited question, you should generate the following migrations:

bundle exec rails g migration add_user_id_to_expense_pictures user:references
bundle exec rails g migration add_expense_picture_id_to_expense_texts expense_picture:references
bundle exec rails g migration add_user_id_to_income_pictures user:references
bundle exec rails g migration add_income_picture_id_to_income_texts income_picture:references

and run them with bundle exec rake db:migrate.

also, you have some of your associations set unproperly. It should be:

class ExpenseText < ActiveRecord::Base
  belongs_to :expense_picture
end

and

class IncomeText < ActiveRecord::Base
  belongs_to :income_picture
end
like image 109
Marek Lipka Avatar answered Sep 20 '22 16:09

Marek Lipka