I had originally created a table with column as
t.string "email", :default => "", :null => false
The requirement has changed and now I need to allow email to be null. How can I write a migration to make :null => true
change_column_null worked perfectly:
change_column_null :users, :email, true
The reverse has a nice option to update existing records (but not set the default) when null is not allowed.
Try:
change_column :table_name, :email, :string, null: true
Related
I have an attribute in tasks table, it's named is_active and it is boolean.But I've forgot to set the default value to this attribute when I was creating a table.So now I'm trying to set this value to true by default,but as I can see from sqlite browser - new tasks are still creating with this value set to NULL.Can you please help me to find where is the problem in my migration?
Migration file:
class AddDefaultValueToTask < ActiveRecord::Migration[5.0]
def change
def up
change_column :tasks, :is_active, :boolean, :default => true
end
def down
change_column :tasks, :is_active, :boolean, :default => nil
end
end
end
Schema.rb file
create_table "tasks", force: :cascade do |t|
t.text "body"
t.boolean "is_active"
t.integer "project_id"
t.string "deadline"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["project_id"], name: "index_tasks_on_project_id"
end
You are missing the hash rocket operator: '=>'
change_column :tasks, :is_active, :boolean, :default => true
Also, if you are using up and down then you need to delete the change block. Both methods cannot be used at the same time
I am developing on Rails 4 with postgres and devise. I have the following User model:
# user model
class User < ActiveRecord::Base
extend FriendlyId
friendly_id :username, :use => :slugged
rolify
devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable
validates :username, :presence => true, :uniqueness => {:case_sensitive => false}, :length => { :minimum => 3 },
:format => { :with => /\A[A-Z0-9a-z\w\b\ \-\_\'\!&##\.]+\z/i,
:message => "may contain only alphanumeric characters and common special characters." }
validates :email, :uniqueness => {:case_sensitive => false}, :presence => true,
:format => { :with => Devise.email_regexp, :message => "isn't valid"}
validates :password, length: { in: 6..128 }, on: :create
validates :password, length: { in: 6..128 }, on: :update, allow_blank: true
validates :slug, :presence => true
end
# in schema
create_table "users", force: true 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
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"
t.datetime "updated_at"
t.string "username"
t.string "slug"
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
add_index "users", ["slug"], name: "index_users_on_slug", unique: true
add_index "users", ["username"], name: "index_users_on_username", unique: true
The fields email and username are unique indices of the users table. My user registration view was created from devise. I create a test account, for instance, with username "test", email "test#example.com", password "123456". I sign out and try to sign up with the same information. I am expecting that the :uniqueness validations to trigger and be rendered on a list of errors alongside the signup form, but instead I get a full-page error with:
ERROR: duplicate key value violates unique constraint "index_users_on_email"
DETAIL: Key (email)=(test#example.com) already exists.
How can I allow this error to bubble up to Rails and be shown as friendly single-line error like "Email is already registered with an account" alongside the sign up form instead of being caught with a big Rails error page?
I've identified the problem. The plugin friendly_id turned out not so friendly. It breaks uniqueness validation and results in 500 internal server errors. I have removed it from my application. Consider using something like ActsAsUrl in the Stringex library. I have removed
extend FriendlyId
friendly_id :username_copy, :use => :slugged
and am now using
acts_as_url :username, :sync_url => true, :url_attribute => :slug
to generate friendly urls.
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
I loaded some seed data in using the code below, and it worked fine. Then, I needed to add two more columns, and I did so using the following steps, but it's not attaching the two new columns seed data to the table, what am I doing wrong?
Steps:
Add two columns using migration
Make them attr_accessible in the model
Replace old CSV file with new CSV file
Change the seed.rb file to plug in the new data
Run rake db:seed
Seed.rb
require 'csv'
Model.delete_all
CSV.foreach("#{Rails.root}/lib/data/model.csv") do |row|
Model.create!(:model_number => row[0], :areq => row[1], :length => row[2], :width => row[3], :depth => row[4], :material => row[5], :frame => row[6], :edge => row[7], :tubes => row[8], :tube_length => row[9])
end
Schema.rb
create_table "models", :force => true do |t|
t.string "model_number"
t.float "areq"
t.float "length"
t.float "width"
t.float "depth"
t.string "material"
t.string "frame"
t.float "edge"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.float "tubes"
t.float "tube_length"
end
Cant say this may work 100%
Try Model.reset_column_information above the seed file once
this should refresh the columns information in table.
require 'csv'
Model.reset_column_information
Model.delete_all
#......
just a guess check if the proper model.csv is getting loaded and have column 8 and 9 means have in all 10 columns.
This is probably in another question, but I cannot find it.
I am a relative noobie to Rails. I am trying to add a new column to a table that already has data in it. This column is not going to allow nulls. What is the easiest way to update all the existing records to have a value in this new column? I know it is probably in the up block of my migration, but I don't know what the syntax would be.
def self.up
change_table :reminders do |t|
t.boolean :active
end
#model name is Reminder - how to update data with a value?
end
What you can do is add the column, update all records in the table with the desired value, then change it to not allow nulls.
def self.up
add_column :reminders, :active, :boolean, :default => true
Reminder.update_all( "active = ?", true )
change_column :reminders, :active, :boolean, :default => true, :null => :false
end
Try this:
def self.up
change_table :reminders do |t|
t.boolean :active, :default => true #or your value
end
#model name is Reminder - how to update data with a value?
end