How to correctly maintain database schema in rails? - ruby-on-rails

I have schema like this:
create_table "grades", force: :cascade do |t|
t.integer "cls"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "post_grades", force: :cascade do |t|
t.integer "post_id"
t.integer "grade_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "posts", force: :cascade do |t|
t.integer "user_id", null: false
t.string "title"
t.text "content"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "user_grades", force: :cascade do |t|
t.integer "user_id"
t.integer "grade_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
In this schema grades, posts and users all are related to each other.
So my first question: Is it correct way of doing this?
Suppose one of user added grade 4 (cls = 4) in his column and another user added same grade. Now I have same value of cls in grade table for two different grade ids.So is there any data redundancy in this schema?

As I got your task, you can go with such solution:
grades -> no references (as it is right now)
user_grades (conventional way to name this table would be grades_users... alphabetical order and both in plural) -> user_id, grade_id (as it is right now)
You don't need post_grades. It's redundant
posts -> grade_id, user_id (if you need author)
Your schema.rb will look smth like:
create_table "users", force: :cascade do |t|
...
end
create_table "grades_users", force: :cascade do |t|
t.integer "user_id"
t.integer "grade_id"
...
end
create_table "grades", force: :cascade do |t|
...
end
create_table "posts", force: :cascade do |t|
t.integer "user_id", null: false
t.integer "grade_id", null: false
...
end

Related

Error- ActiveModel::UnknownAttributeError: unknown attribute 'name' for Review

When I run:
rails db:seed
in the command line, I get the following error:
ActiveModel::UnknownAttributeError: unknown attribute 'name' for Review..........................................................
I also get the same error when I run:
rails db:seed
seeds.rb
movie = Movie.find_by(title: 'Iron Man')
movie.reviews.create!(name: "Roger Ebert", stars: 3, comment: "I laughed, I cried, I spilled my popcorn!")
movie.reviews.create!(name: "Gene Siskel", stars: 5, comment: "I'm a better reviewer than he is.")
movie.reviews.create!(name: "Peter Travers", stars: 4, comment: "It's been years since a movie superhero was this fierce and this funny.")
movie = Movie.find_by(title: 'Superman')
movie.reviews.create!(name: "Elvis Mitchell", stars: 5, comment: "It's a bird, it's a plane, it's a blockbuster!")
Genre.create!(name: "Action")
Genre.create!(name: "Comedy")
Genre.create!(name: "Drama")
Genre.create!(name: "Romance")
Genre.create!(name: "Thriller")
Genre.create!(name: "Fantasy")
Genre.create!(name: "Documentary")
Genre.create!(name: "Adventure")
Genre.create!(name: "Animation")
Genre.create!(name: "Sci-Fi")
Here is my schema filee [sic]:
ActiveRecord::Schema.define(version: 20181218222845) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "characterizations", force: :cascade do |t|
t.bigint "movie_id"
t.bigint "genre_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["genre_id"], name: "index_characterizations_on_genre_id"
t.index ["movie_id"], name: "index_characterizations_on_movie_id"
end
create_table "favorites", force: :cascade do |t|
t.bigint "movie_id"
t.bigint "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["movie_id"], name: "index_favorites_on_movie_id"
t.index ["user_id"], name: "index_favorites_on_user_id"
end
create_table "genres", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "movies", force: :cascade do |t|
t.string "title"
t.string "rating"
t.decimal "total_gross"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.text "description"
t.date "released_on"
t.string "cast"
t.string "director"
t.string "duration"
t.string "image_file_name", default: ""
t.string "image_content_type"
t.integer "image_file_size"
t.datetime "image_updated_at"
t.string "main_image"
t.string "slug"
end
create_table "reviews", force: :cascade do |t|
t.integer "stars"
t.text "comment"
t.bigint "movie_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "user_id"
t.index ["movie_id"], name: "index_reviews_on_movie_id"
end
create_table "users", force: :cascade do |t|
t.string "name"
t.string "email"
t.string "password_digest"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "username"
t.boolean "admin", default: false
end
add_foreign_key "characterizations", "genres"
add_foreign_key "characterizations", "movies"
add_foreign_key "favorites", "movies"
add_foreign_key "favorites", "users"
add_foreign_key "reviews", "movies"
end
Your reviews table does not have a name column, which is what Rails is telling you.
I don’t know how your app works, but I do see a user_id column on the reviews table, and the users table has a name column, so I imagine you need to create a user using that name attribute, and then pass the user into the review that you’re creating.
Without seeing your Review and User model, I can’t speak for sure.
At a minimum, you'll need to create a migration & run it to add the name field to your reviews table:
rails generate migration AddNameToReviews name:string
rails db:migrate
This should fix your reported error.

Create Association Through Two Different Models

I have the following models:
User:
User
has_and_belongs_to_many :user_jobs, foreign_key: "user_id", class_name: "Job"
has_many :jobs, through: :locations
has_many :customers, through: :locations
has_and_belongs_to_many :locations
Location:
Location
has_and_belongs_to_many :users
has_and_belongs_to_many :customers
has_many :jobs
Customer:
Customer
has_many :jobs, dependent: :destroy
has_and_belongs_to_many :locations
Job:
Job
belongs_to :customer
belongs_to :location
has_and_belongs_to_many :users
Here is my Schema.rb file
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more
migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20180308214356) do
create_table "accounts", force: :cascade do |t|
t.string "name"
t.text "company_name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.text "stripe_publishable_key"
t.text "stripe_account_id"
t.text "twilio_account_sid"
t.text "twilio_auth_token"
end
create_table "categories", force: :cascade do |t|
t.string "name"
t.text "description"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "location_id"
t.index ["location_id"], name: "index_categories_on_location_id"
end
create_table "customers", force: :cascade do |t|
t.string "first_name"
t.string "middle_initial"
t.string "last_name"
t.datetime "updated_at", null: false
t.integer "account_id"
t.text "stripe_customer_id"
t.index ["account_id"], name: "index_customers_on_account_id"
end
create_table "customers_locations", id: false, force: :cascade do |t|
t.integer "location_id", null: false
t.integer "customer_id", null: false
end
create_table "drafts", force: :cascade do |t|
t.string "phone_one"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "jobs", force: :cascade do |t|
t.date "date"
t.integer "time"
t.boolean "time_sensitive"
t.text "address_line_one"
t.text "address_line_two"
t.string "city"
t.string "state"
t.string "zip"
t.text "special_instructions"
t.text "description"
t.text "work_completed"
t.text "billing_information"
t.text "notes"
t.string "status"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["customer_id"], name: "index_jobs_on_customer_id"
t.index ["location_id"], name: "index_jobs_on_location_id"
end
create_table "jobs_users", id: false, force: :cascade do |t|
t.integer "user_id", null: false
t.integer "job_id", null: false
end
create_table "locations", force: :cascade do |t|
t.string "name"
t.text "description"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "account_id"
t.index ["account_id"], name: "index_locations_on_account_id"
end
create_table "locations_users", id: false, force: :cascade do |t|
t.integer "user_id", null: false
t.integer "location_id", null: false
end
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "location_id"
t.integer "account_id"
t.integer "role_id"
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["location_id"], name: "index_users_on_location_id"
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
t.index ["role_id"], name: "index_users_on_role_id"
end
end
With this model structure I can query the jobs model in two different ways. First user.user_jobs and user.jobs. Both of these queries return two different result sets. I need to be able to do the same thing with the customers. I can currently query user.customers but I do not know what syntax I should use to make user.user_customers work so that the query joins with the users' related jobs and then grabs the customers related to those jobs. My current query joins the users' locations and grabs the customers associated with those locations. Thanks in advance!
has_many :user_job_customers, through: :user_jobs, source: 'customers'
has_many :location_customers, through: :locations, source: 'customers'
I guess you need :source option

Can't sort by rails index

I used the rails globalize and I18n gem. But now I can't sort my model. Can you guys help?
I tried adding a new index, but I'm not entirely familiar with indexing.
Controller.rb
def index
#foods = Food.all.order(:name)
add_breadcrumb "index", foods_path
end
Schema
create_table "food_translations", force: :cascade do |t|
t.integer "food_id", null: false
t.string "locale", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "name"
t.string "bio"
end
add_index "food_translations", ["food_id"], name: "index_food_translations_on_food_id", using: :btree
add_index "food_translations", ["locale"], name: "index_food_translations_on_locale", using: :btree
add_index "food_translations", ["name"], name: "index_food_translations_on_name", using: :btree
create_table "foods", force: :cascade do |t|
t.string "address"
t.string "phone"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "image_file_name"
t.string "image_content_type"
t.integer "image_file_size"
t.datetime "image_updated_at"
t.string "yelp"
t.string "youtube"
end
Yes, you will need a join. If you do not have a model for the translation, you could just use .joins for your finder. Like:
Food.joins('INNER JOIN food_translations ON foods.id=food_translations.food_id')
.order('food_translations.name').where('food_translations.locale=xxx')
ps: I wonder why you do not have a index on "food_id" AND "locale" which should be uniq. In your case you can have two or more translations for 1 food in the same language.

RoR: Cannot Migrate Database to Heroku

I am having trouble migrating my database to Heroku. I have checked the other issues that address this to no avail. I can really use a second pair of eyes on my code to help me figure this out.
This is the error I get:
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:
PG::UndefinedTable: ERROR: relation "props" does not exist
: ALTER TABLE "comments" ADD CONSTRAINT "fk_rails_1d3f70cf04"
FOREIGN KEY ("prop_id")
REFERENCES "props" ("id")
It seems to get caught while migrating this file:
class CreateComments < ActiveRecord::Migration
def change
create_table :comments do |t|
t.string :commenter
t.text :body
t.references :prop, index: true, foreign_key: true
t.timestamps null: false
end
end
end
This is the migration file where I create the table props:
class CreateProps < ActiveRecord::Migration
def change
create_table :props do |t|
t.string :title
t.text :text
t.references :user, index: true, foreign_key: true
t.timestamps null: false
end
end
end
My schema is here:
ActiveRecord::Schema.define(version: 20160528205746) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "answers", force: :cascade do |t|
t.string "choice"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "created_by"
t.integer "user_id"
t.integer "prop_id"
end
create_table "comments", force: :cascade do |t|
t.string "commenter"
t.text "body"
t.integer "prop_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "comments", ["prop_id"], name: "index_comments_on_prop_id", using: :btree
create_table "props", force: :cascade do |t|
t.string "title"
t.text "text"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "choice"
t.string "answer"
t.integer "answerId"
end
add_index "props", ["user_id"], name: "index_props_on_user_id", using: :btree
create_table "user_answers", force: :cascade do |t|
t.integer "user_id"
t.integer "answer_id"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "users", force: :cascade do |t|
t.string "username"
t.string "email"
t.integer "score", default: 0
t.integer "prop_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "password_digest"
t.string "created_by"
t.boolean "admin", default: false
t.integer "answers_id"
t.integer "answer_id"
end
add_index "users", ["answer_id"], name: "index_users_on_answer_id", using: :btree
add_index "users", ["prop_id"], name: "index_users_on_prop_id", using: :btree
create_table "wins", force: :cascade do |t|
t.string "correctAnswer"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "wins", ["user_id"], name: "index_wins_on_user_id", using: :btree
add_foreign_key "users", "answers"
end
The problem is you are creating a reference to a table that is not yet created. Remove the reference from that migration to props, then add the props table and then add a migration implementing the association. If you dont need the data currently in the db I would do a "rake db:drop" and edit the migration files (only if you arent collaborating with others!)
Update:
Do rails g migration add_ref_to_comments
Then edit the migration to have:
def change
add_reference :props, :comment, index: true
end

Application_controller define method to only show future dates

In my Ruby on Rails application I have a cinema system and am trying to show only show times for films that are either in the future or today (so not in the past).
I am trying to do this in my _form.html.erb in a drop down menu:
<%= f.grouped_collection_select :showing_id, live_films.order(:title), :showings, :title, :id, :showing_times %>
Where live_films is the method in application_controller.rb:
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
helper_method :active_menu, :live_films
def live_films
Film.includes(:showings).where('showings.show_date > ?', Date.current.beginning_of_day)
end
end
But I get this error:
ActiveRecord::StatementInvalid in Bookings#new
SQLite3::SQLException: no such column: showings.show_date: SELECT "films".* FROM "films" WHERE (showings.show_date > '2015-02-20 00:00:00.000000') ORDER BY "films"."title" ASC
My db/schema:
ActiveRecord::Schema.define(version: 20150219091141) do
create_table "bookings", force: :cascade do |t|
t.integer "user_id"
t.integer "showing_id"
t.integer "seat_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "categories", force: :cascade do |t|
t.string "genre"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "certificates", force: :cascade do |t|
t.string "age_rating"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "certificate_img_url"
end
create_table "films", force: :cascade do |t|
t.string "title"
t.string "synopsis"
t.string "director"
t.string "cast1"
t.string "cast2"
t.string "cast3"
t.date "release_date"
t.string "warnings"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "image_url"
t.string "certificate_id"
t.integer "category_id"
t.integer "hours"
t.integer "minutes"
t.string "video_url"
end
create_table "screens", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "seats", force: :cascade do |t|
t.string "row_letter"
t.integer "row_number"
t.integer "screen_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "showings", force: :cascade do |t|
t.date "show_date"
t.time "show_time"
t.integer "film_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "screen_id"
end
add_index "showings", ["film_id"], name: "index_showings_on_film_id"
create_table "users", force: :cascade do |t|
t.string "password_digest"
t.string "role"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "first_name"
t.string "last_name"
t.string "house_no"
t.string "street"
t.string "town"
t.string "postcode"
t.string "email"
end
The column name show_date is correct as is the table name showings but for some reason it isn't working.
Can someone please help?
Here is the solution:
Film.joins(:showings).where('showings.show_date > ?', Date.current.beginning_of_day).preload(:showings)

Resources