How to add a new column in a migration file - sql

I'm using Ruby on rails and Sqlite and I got the rspec and factorybot gems. And i'm on Linux ubuntu.
Migration
class CreateArticles < ActiveRecord::Migration[6.0]
def change
create_table :articles do |t|
t.string :title
t.string :description
t.integer :price
t.string :picture
t.string :author
t.timestamps
end
end
end
Schema.rb
ActiveRecord::Schema.define(version: 2020_02_07_071425) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "articles", force: :cascade do |t|
t.string "title"
t.string "description"
t.integer "price"
t.string "picture"
t.string "author"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end
end
article.rb
FactoryBot.define do
factory :article do
title { Faker::Company.name }
description { Faker::Lorem.paragraph(sentence_count: 35)}
price { Faker::Number.decimal(l_digits: 2) }
picture { Faker::Company.logo }
author { Faker::FunnyName.two_word_name }
end
end
I just want add a new row like counter 0, but I tried everything (db:migrate, reset, modify all files..) every time my counter is undefined.
What do I need to do?

Related

How to write the active record query

I have three models in context of this question:
class ClearanceBatch < ActiveRecord::Base
has_many :items
belongs_to :user
end
class Item < ActiveRecord::Base
belongs_to :style
belongs_to :user
belongs_to :clearance_batch
validates :id, :uniqueness => true
end
class User < ActiveRecord::Base
has_many :items, dependent: :destroy
has_many :clearance_batches, dependent: :destroy
enum role: {staff: 0, vendor: 1, admin: 2}
end
Schema:
create_table "clearance_batches", force: :cascade do |t|
t.datetime "created_at"
t.datetime "updated_at"
t.boolean "status", default: false
t.string "boughtby", default: ""
t.integer "user_id"
end
add_index "clearance_batches", ["user_id"], name: "index_clearance_batches_on_user_id"
create_table "items", force: :cascade do |t|
t.string "size"
t.string "color"
t.string "status"
t.decimal "price_sold"
t.datetime "sold_at"
t.integer "style_id"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "clearance_batch_id"
t.integer "user_id"
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 "role", default: 0
end
I want to find all items in a batch of the currently logged in user(mainly vendor) with the status "clearanced", and get their details in a loop from controller to my view
Can anyone please help me out with the active record query? Please! :)
The SQLite Query I think would be:
Select I.id from clearance_batches C INNER JOINS Items I on C.id = I.clearance_batch_id where C.user_id = "1" and I.status = "clearanced"
(If 1 is the current user, keeping in mind I am only allowing user of role vendors to be a user in clearance_batch table)
(1) Query:
Items.where(status: "clearanced")
.joins(:clearance_batches)
.where(clearance_batches: {user_id: current_user})
(2) Controller:
#clearanced_items = query(1)
(3) View:
<% #clearanced_items.each do |c_item| %>
...
<% end %>

How can i use data from antoher tables in a active record where in rails

im trying to make a search form in a table that contains two ids as values, one of them is the id of an user and the other is the id of a project.
Here is my database schema:
create_table "users", force: :cascade do |t|
t.string "name"
t.string "email"
t.text "bio"
t.float "lastLatitude"
t.float "lastLongitude"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "swipes"
t.string "profile_image"
end
create_table "projects", force: :cascade do |t|
t.string "name"
t.text "bio"
t.integer "user_id"
t.string "salary"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "likes"
t.string "image"
t.float "latitude"
t.float "longitude"
end
create_table "matches", force: :cascade do |t|
t.integer "user_id"
t.integer "project_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
What i want to do is to create a search form in the matches index view to filter the matches by the user name or the project name, but i don't know how to do it, this is what i have right now:
def self.search(search)
if search
where('User(user_id).name LIKE :search OR Project.name LIKE :search', search: "%#{search}%")
else
where(nil)
end
end
Is it possible to do that?
Any help is welcome
I suggest a scope approach
class Match < ActiveRecord::Base
belongs_to :project
belongs_to :user
scope name, ->(n) {
joins(:user, :project).where("users.name like ? or projects.name like ? ", "%#{n}%", "%#{n}%")
}
end
class User < ActiveRecord::Base
has_many :projects
scope :name, ->(n) {
where("users.name like ?", "%n%")
}
end
class Project < ActiveRecord::Base
scope :name, ->(n) {
where("projects.name like ?", "%n%")
}
end

Testing with rspec is causing an error: `Migrations are pending. To resolve this issue, run: bin/rake db:migrate RAILS_ENV=development `

when I run the rails server, localhost displays this error:
ActiveRecord::PendingMigrationError (Migrations are pending.
To resolve this issue, run: bin/rake db:migrate RAILS_ENV=development):
I have run the bin/rake... and the next error says:
$ bundle exec bin/rake db:migrate RAILS_ENV=development
== 20150225172130 CreateVotes:
migrating ======================================
-- create_table(:votes)
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:
SQLite3::SQLException: table "votes" already exists: CREATE TABLE "votes"
("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "value" varchar(255),
"user_id" integer, "post_id" integer, "created_at" datetime, "updated_at"
datetime)
_create_votes.rb
class CreateVotes < ActiveRecord::Migration
def change
create_table :votes do |t|
t.string :value
t.references :user, index: true
t.references :post, index: true
t.timestamps
end
end
end
Basically, it tells me I have migrations pending, but when I attempt to migrate it says the table already exists.
20150225172130 CreateVotes:
migrating ======================================
-- create_table(:votes)
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:
SQLite3::SQLException: table "votes" already exists: CREATE TABLE "votes"...
after running db:drop:all
db:create
db:migrate
db:test:clone
votes are now showing up in schema.rb:
ActiveRecord::Schema.define(version: 20150101200224) do
create_table "comments", force: true do |t|
t.text "body"
t.integer "post_id"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "comments", ["post_id"], name: "index_comments_on_post_id"
create_table "posts", force: true do |t|
t.string "title"
t.text "body"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "users", force: true do |t|
t.string "name"
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.string "confirmation_token"
t.datetime "confirmed_at"
t.datetime "confirmation_sent_at"
t.string "unconfirmed_email"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "users", ["email"], name: "index_users_on_email", unique: true
add_index "users", ["reset_password_token"], name:"index_users_on_reset_password_token", unique: true
create_table "votes", force: true do |t|
t.integer "value"
t.integer "user_id"
t.integer "post_id"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "votes", ["post_id"], name: "index_votes_on_post_id"
add_index "votes", ["user_id"], name: "index_votes_on_user_id"
end
model/vote.rb
class Vote < ActiveRecord::Base
belongs_to :user
belongs_to :post
end
You could do this:
class CreateVotes < ActiveRecord::Migration
def change
unless table_exists? :votes
create_table :votes do |t|
t.string :value
t.references :user, index: true
t.references :post, index: true
t.timestamps
end
end
end
I've run into this before when a migration didn't run as expected. But you should also check your schema.rb file to make sure that the votes table has the columns that the migration adds.

ActsAsTaggableOn after own tag implementation

I had my own implementation of tags in my rails application and wanted to replace it by the ActsAsTaggableOn gem. I generated the migration and deleted all the migrations with tags in it, but forgot to rollback first, so I just did rake db:reset. Now the schema looks fine with tag and taggable in it, but if I try Tags out in the Console, by just typing Tag i get
NameError: uninitialized constant Tag
What causes this error, I thought I just did like in the Railscast.
My schema.rb looks like this:
# encoding: UTF-8
# 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 to check this file into your version control system.
ActiveRecord::Schema.define(:version => 20121009203921) do
create_table "comments", :force => true do |t|
t.text "content"
t.integer "user_id"
t.integer "message_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "events", :force => true do |t|
t.string "name"
t.datetime "start_at"
t.datetime "end_at"
t.integer "user_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "messages", :force => true do |t|
t.text "content"
t.integer "user_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "taggings", :force => true do |t|
t.integer "tag_id"
t.integer "taggable_id"
t.string "taggable_type"
t.integer "tagger_id"
t.string "tagger_type"
t.string "context", :limit => 128
t.datetime "created_at"
end
add_index "taggings", ["tag_id"], :name => "index_taggings_on_tag_id"
add_index "taggings", ["taggable_id", "taggable_type", "context"], :name => "index_taggings_on_taggable_id_and_taggable_type_and_context"
create_table "tags", :force => true do |t|
t.string "name"
end
create_table "users", :force => true do |t|
t.string "name"
t.string "email"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.string "encrypted_password"
t.string "salt"
t.boolean "admin", :default => false
t.string "phone"
t.string "street"
t.string "zip"
t.string "location"
end
add_index "users", ["email"], :name => "index_users_on_email", :unique => true
end
Thanks for your help!
I had to have a model, to get it work in the console.

rails add_column with default value but the default value don't take effect

My rails version is 3.2.8 and use the default database.
This is my migration code:
class AddQuantityToLineItem < ActiveRecord::Migration
def change
add_column :line_items, :quantity, :integer,:default=>1
end
end
I find a explaination about :default option here and as it said,when i create a
new LineItem ,it should have a default quantity=1,but here is what i get from rails console:
lineb=LineItem.new
#<LineItem id: nil, product_id: nil, cart_id: nil, created_at: nil, updated_at: nil, quantity: nil>
And when i get LineItem from the database,the quantity field is nil
too.
And here is the db/schema.rb :
ActiveRecord::Schema.define(:version => 20121008065102) do
create_table "carts", :force => true do |t|
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "line_items", :force => true do |t|
t.integer "product_id"
t.integer "cart_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.integer "quantity"
end
create_table "products", :force => true do |t|
t.string "title"
t.text "description"
t.string "image_url"
t.decimal "price", :precision => 8, :scale => 2
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
end
Your migration should work fine. Based on your schema though it looks like it hasn't actually taken effect, since t.integer "quantity" has no default value.
The line in the schema for quantity should look like this:
t.integer "quantity", :default => 1
Make sure you have actually run your migration (bundle exec rake db:migrate), and if that doesn't work then rollback (bundle exec rake db:rollback) and run the migration again (as #surase.prasad suggested).