Adding attribute to already existing model - sql

I am trying to add user:references onto my already existing model. This is what I originally wrote:
rails g model Post title:string description:text
I do this to add the user:references by running rails generate migration add_user_to_posts user:references, I am receiving this error upon running rake db:migrate:
-- create_table(:users)
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:
SQLite3::SQLException: table "users" already exists
I am reading the error and I understand I already have a User model, however, I want to add this attribute to the Post model, not the User model.
Db file:
Posts:
class CreatePosts < ActiveRecord::Migration[5.0]
def change
create_table :posts do |t|
t.string :title
t.text :description
t.timestamps
end
end
end
Trying to add the user to posts:
class AddUserToPosts < ActiveRecord::Migration[5.0]
def change
add_reference :posts, :user, foreign_key: true
end
end
Users:
class CreateUsers < ActiveRecord::Migration[5.0]
def change
create_table :users do |t|
t.string :name
t.string :uid
t.string :avatar_url
t.timestamps
end
add_index :users, :uid
end
end
However, rake db:migrate gives me the error above.

Related

Database associations causing issues in db migration with postgres

I've been making a basic schema for a rails app but when I try to migrate it using rails db:migrate, it gives me some weird association errors that I'm not sure what's causing.
== 20211001092658 CreateDevelopers: migrating =================================
-- create_table(:developers)
-> 0.0076s
== 20211001092658 CreateDevelopers: migrated (0.0077s) ========================
== 20211001093122 CreateMessages: migrating ===================================
-- create_table(:messages)
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:
PG::UndefinedTable: ERROR: relation "teams" does not exist
/home/nero/Projects/SMS-Rails/db/migrate/20211001093122_create_messages.rb:3:in `change'
Caused by:
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: relation "teams" does not exist
/home/nero/Projects/SMS-Rails/db/migrate/20211001093122_create_messages.rb:3:in `change'
Caused by:
PG::UndefinedTable: ERROR: relation "teams" does not exist
/home/nero/Projects/SMS-Rails/db/migrate/20211001093122_create_messages.rb:3:in `change'
Tasks: TOP => db:migrate
I've been having a few issues setting up Postgres on my machine but I figured most of it would be solved after I created the role, password and database.
Migration files:
#developers
class CreateDevelopers < ActiveRecord::Migration[6.1]
def change
create_table :developers do |t|
t.string :full_name
t.string :email
t.string :mobile
t.timestamps
end
end
end
#teams
class CreateTeams < ActiveRecord::Migration[6.1]
def change
create_table :teams do |t|
t.string :name
t.string :dept_name
t.string :dev_ids, array: true, default: []
t.timestamps
end
end
end
#messages
class CreateMessages < ActiveRecord::Migration[6.1]
def change
create_table :messages do |t|
t.references :team, null: false, foreign_key: true
t.string :title
t.text :content
t.timestamps
end
end
end

using activeuuid gem for existing database in rails

I need to implement activeuuid gem to have UUIDs instead of default Rails ids. we can implement it for creating new migration as:
class CreateStudents < ActiveRecord::Migration
def change
create_table :students, :id => false do |t|
t.uuid :id, :primary_key => true
t.string :name
t.string :email
t.timestamps
end
end
end
And in model we include ActiveUUID::UUID as:
class Student < ActiveRecord::Base
attr_accessible :email, :name
include ActiveUUID::UUID
end
Now I already have a database so how can I implement the activeuuid gem to have UUIDs instead of default Rails ids for existing DB?
Need to make changes in all migrations or what?
Need help in this regard. thanks
The UUID is stored as a binary field w/ 16 positions as I found here: https://github.com/jashmenn/activeuuid/blob/master/lib/activeuuid/patches.rb#L62
It worked for me (existing table without records):
def change
reversible do |dir|
change_table :payments do |t|
dir.up { t.change :id, :binary, limit: 16, :primary_key => true }
dir.down { t.change :id, :integer }
end
end
end
Don't forget to add those lines to your model as well:
include ActiveUUID::UUID
natural_key :at_least_one_field_here
More info in the github repo: https://github.com/jashmenn/activeuuid/

cant mass assign the protected attributes

iam working in rails 3.while trying to creating a user i am getting
cant mass assign the protected attributes error
I included following gems in the gemfile
gem 'authlogic'
gem 'gemcutter'
and run bundle install in rails console
then create a a user model and add the required authlogic columns to the migration.
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :login, :null => false
t.string :crypted_password, :null => false
t.string :password_salt, :null => false
t.string :persistence_token, :null => false
t.timestamps
end
end
end
and did rake db:migrate
Included authlogic in the user model.
# /app/models/user.rb
class User < ActiveRecord::Base
acts_as_authentic
end
while trying to create a user in rails console User.create(name: "pria",password: "priya123", password_confirmation: "priya123")
iam getting
cant mass assign the protected attributes :name, :password, :password_confirmation
How can i rectify this error!
In your User model:
attr_accessible :name, :password, :password_confirmation
You must add these attributes to the attr_accessible list in your model.
For important information about mass-assignment and its security implications: http://guides.rubyonrails.org/security.html#mass-assignment

Unique model field at databse level in Rails 3.1+ migration?

Is there a way to specify a database level uniqueness constraint on a field in a Rails 3.1+ migration? I know ActiveRecord's validates_uniqueness_of would work, but I'm curious to know if this can be specified elsewhere.
For example, in order to specify that the 'login' field should be unique in a migration such as ...
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name
t.string :login
t.timestamps
end
end
end
... I'd like to add an option like :unique => true.
There's nothing mentioned in the Documentation so I assume that's not a great place/way to do things, but does anyone know how this might be achieved (even if it's manually added to the resulting schema)? Or is validates_uniqueness_of the preferred way to go?
You can add unique index so:
def change
create_table :users do |t|
t.string :name
t.string :login
t.timestamps
end
add_index :users, :login, :unique => true
end

How do I add columns to devise after the initial create_table rake?

I installed Devise, raked, and then realized afterwards, that I want to add :confirmable.
Can I go back to the same initial migration and just uncomment out the helper that I want and then rake db:migrate again?
I tried it and it didn't seem to work. But I haven't seen an example of how to create a follow-on migration.
Thanks!
This is what I tried:
1 class AddConfirmableToUsers < ActiveRecord::Migration
2 def self.up
3 change_table :users do |t|
4 t.confirmable
5 end
6 add_index :users, :confirmation_token, :unique => true
7 end
8
9 def self.down
10 remove_column :users, :confirmation_token
11 end
12
13 end
You can add the proper columns yourself like so:
class AddConfirmableToUsers < ActiveRecord::Migration
def self.up
change_table :users do |t|
t.string :confirmation_token
t.datetime :confirmed_at
t.datetime :confirmation_sent_at
end
add_index :users, :confirmation_token, :unique => true
end
def self.down
change_table :users do |t|
t.remove :confirmation_token, :confirmed_at, :confirmation_sent_at
end
remove_index :users, :confirmation_token
end
end
Your migration should work. Did you check your User model to make sure :confirmable is enabled? It's commented out by default.
If you don't mind losing your data you can just do
> rake db:drop
Otherwise you can just edit the initial migration and do a rollback.
# get the current migration version
> rake db:version
> Current version: ****************41
> rake db:rollback ****************40
Make your changes
> rake db:migrate