I have a model which has some information which is best stored as a serialized Hash on the model, as it is unimportant to most of the app and varies from instance to instance:
class Foo < AR::Base
attr_accessible :name, :fields
serialize :fields
end
I have realised that one of the common entries in fields actually is relevant to the app, and would be better placed as an attribute (layout).
Bearing in mind that I should not, ideally, refer to models in migrations, how can I write a migration to add the layout field, and initialise it with the value currently in the fields Hash?
class AddLayoutToCardTemplates < ActiveRecord::Migration
def change
add_column :card_templates, :layout, :string, default: 'normal'
# Initialise `layout` from `fields['layout']`... how? With raw SQL?
end
end
You should not refer to models in your app folder. This doesn't mean you cannot create local model. :)
class AddLayoutToCardTemplates < ActiveRecord::Migration
class Foo < AR::Base
attr_accessible :name, :fields
serialize :fields
end
def change
add_column :card_templates, :layout, :string, default: 'normal'
Foo.all.each do |f|
f.layout = f.fields.delete(:layout)
f.save
end
end
That way your migration can use ActiveRecord goodies and yet stays time-independent, as your real model in app folder is never loaded.
Related
I'm new in rails. I read rencently how to serialize an array of string for example to store it in database.
class Fle < ActiveRecord::Base
serialze :etat_fle
end
But i don't know how to represent this serialized field in the corresponding ActiveRecord::Migration
Have someone an idea ?
Store it as a text. If the table is already created -
add_column :table, :column, :text
As Major Major said, i have to declare the field like this in my migration file
t.column :type_fle, :text
and additionnaly i have to declare the field prefixed by the word serialize in my ActiveRecord::Base file
serialize :type_fle
class AddRatingToBooks < ActiveRecord::Migration
def up
add_column :books, :rating, :integer
end
def down
remove_column :books, :rating
end
I have the following snippet of code in my db/migrate/, I'm trying to add ratings to my books table, where it would be in a range from 0-100, but I'm not sure how to add that here, all i could find was querying with ranges. I'm sure it's simple I'm just not there yet.
You don't need to specify the range of integer values in your migration file. The migration file is simply used to add the database column to store the rating. This is not the place to add validations.
You should use your Book model to specify a validation that ensures your ratings fall within a certain range. Something like this:
class Book < ActiveRecord::Base
validates :rating, :inclusion => { :in => 0..100 }
end
I would highly recommend reading the Rails guides on both migrations and validations.
Probably I'm too late with the answer. But it's possible to define validation on db level with Migration Validators project: https://github.com/vprokopchuk256/mv-core
As example, in your migration:
def change
change_table :books do |t|
t.integer :rating, inclusion: 0..100
end
end
and then in your model:
class Book < ActiveRecord::Base
enforce_migration_validations
end
As result your validation will be defined both in db ( as statement inside trigger or check constraint, depending on your db) and on your model
SQL ( PostgreSQL ):
=# insert into books(rating) values(10);
INSERT 0 1
=# insert into books(rating) values(200);
ERROR: new row for relation "books" violates check constraint "chk_mv_books_rating"
Rails console:
Book.new(title: 10).valid?
=> true
Book.new(title: 200).valid?
=> false
My model (Bar) already has a reference column, let's call it foo_id and now I need to change foo_id to fooable_id and make it polymorphic.
I figure I have two options:
Create new reference column fooable which is polymorphic and migrate the ID's from foo_id (What would be the best way to migrate these? Could I just do Bar.each { |b| b.fooable_id = b.foo_id }?
Rename foo_id to fooable_id and add polymorphic to fooable_id. How to add polymorpic to an existing column?
1. Change the name of foo_id to fooable_id by renaming it in a migration like:
rename_column :bars, :foo_id, :fooable_id
2. and add polymorphism to it by adding the required foo_type column in a migration:
add_column :bars, :fooable_type, :string
3. and in your model:
class Bar < ActiveRecord::Base
belongs_to :fooable,
polymorphic: true
end
4. Finally seed the type of you already associated type like:
Bar.update_all(fooable_type: 'Foo')
Read Define polymorphic ActiveRecord model association!
Update for Rails >= 4.2
TLDR
add new reference
copy reference ids
remove old reference
So the migration is:
def change
add_reference :bars, :fooable, polymorphic: true
reversible do |dir|
dir.up { Bar.update_all("fooable_id = foo_id, fooable_type='Foo'") }
dir.down { Bar.update_all('foo_id = fooable_id') }
end
remove_reference :bars, :foo, index: true, foreign_key: true
end
Background
Current Rails generates references with index and foreign_key, which is a good thing.
This means that the answer of #Christian Rolle is no longer valid as after renaming foo_id it leaves a foreign_key on bars.fooable_id referencing foo.id which is invalid for other fooables.
Luckily, also the migrations evolve, so undoable migrations for references do exist.
Instead of renaming the reference id, you need to create a new reference and remove the old one.
What's new is the need to migrate the ids from the old reference to the new one.
This could be done by a
Bar.find_each { |bar| bar.update fooable_id: bar.foo_id }
but this can be very slow when there are already many relations. Bar.update_all does it on database level, which is much faster.
Of course, you should be able to roll back the migration, so when using foreign_keys the complete migration is:
def change
add_reference :bars, :fooable, polymorphic: true
reversible do |dir|
dir.up { Bar.update_all("fooable_id = foo_id, fooable_type='Foo'") }
dir.down { Bar.update_all('foo_id = fooable_id') }
end
remove_reference :bars, :foo, index: true, foreign_key: true
end
Remember that during rollback, change is processed from bottom to top, so foo_id is created before the update_all and everything is fine.
One small change I would make is to the migration:
#db/migrate/latest.rb
class Latest
def change
rename_column :bars, :foo_id, :fooable_id
add_column :bars, :fooable_type, :string, after: :id, default: 'Foo'
end
end
This would eliminate the need to do a data migration.
Update: this will work on rails 3 and up. According to the question the original base class is implied to be Foo.
In reference to your question specifically, here's what I'd do:
All the data in your Bar model is going to be stored in reference to the Bar model. This means that if you change the foo_id attribute in your model, you'll be able to just populate the bar_type attribute you need to add (as they'll all be able to reference the same model)
The way to do this is as follows:
Create migration for foo_id > fooable_id
Insert a fooable_type column
In rails console, loop through all existing records of Bar, filling the fooable_type column
First things first:
$ rails g migration ChangeFooID
#db/migrate/latest.rb
class Latest
def change
rename_column :bars, :foo_id, :fooable_id
add_column :bars, :fooable_type, :string, after: :id
end
end
This will create the various columns for you. Then you just need to be able to cycle through the records & change the type column:
rails c
Bar.find_each do |bar|
bar.update(barable_type: "Foo")
end
This will allow you to change the type of your columns, giving you the ability to associate all the current records with the respective records.
Polymorphism
You'll be able to use the Rails docs as a reference as to how to associate your models:
#app/models/foo.rb
class Foo < ActiveRecord::Base
has_many :bars, as: :barable
end
#app/models/bar.rb
class Bar < ActiveRecord::Base
belongs_to :foo, polymorphic: true
end
I'm in the following situation, taking over an existing website, I have model User which has many devices like that:
has_many :devices, :through => :credits
When I create a device it creates a credit, but some of the attributes of the credits are null. I'd like to know if there's a way to control the creation of this credit and make sure nothing is null in the credit created for the database.
Thanks in advance
Recommended:
Use default values in your credits database table. You can use a database migration to do this.
class AddDefaultValuesToCredits < ActiveRecord::Migration
def change
change_column :credits, :value1, :boolean, default: false
change_column :credits, :value2, :string, default: 'words'
# change other columns
end
end
If no explicit value is specified for value1 or value2, they'll default to false and 'words', respectively.
Alternative: You can also set default values in your Credit model.
class Credit < ActiveRecord::Base
after_initialize :set_values, unless: persisted?
# other model code
def set_values
if self.new_record?
self.value1 = false if self.value.nil? # initial boolean value
self.value2 ||= 'words' # initial string value
# other values
end
end
I'm trying to add a column called share to one of my resources.
The idea is that users can upload documents and share them with other (specific) users, and the array contains the emails of those that the user wants to share with.
I tried adding a migration with the code
class AddShareToDocuments < ActiveRecord::Migration
def change
add_column :documents, :share, :array, :default => []
end
end
But when I open up rails console in the command prompt, it says that share:nil and user.document.share.class is NilClass.
Creating a new array in the rails console sandbox by typing
newarray = []
says that newarray.class is Array.
Can anyone spot what I'm doing wrong?
Rails 4 the PostgreSQL Array data type
In terminal
$ rails generate migration AddTagsToProduct tags:string
Migration file:
class AddTagsToProduct < ActiveRecord::Migration
def change
add_column :products, :tags, :string, array: true, default: []
end
end
https://coderwall.com/p/sud9ja/rails-4-the-postgresql-array-data-type
if you want support all databases you must serialize the array in a String
class Documents < ActiveRecord::Base
serialize :share
end
class AddShareToDocuments < ActiveRecord::Migration
def change
add_column :documents, :share, :string, :default => []
end
end
In case of Postgresql and array datatype I found https://coderwall.com/p/sud9ja
Arrays are not normally a type to be stored in a database. As michelemina points out, you can serialize them into a string and store them, if the type of the data in the array is simple (strings, int, etc). For your case of emails, you could do this.
If, on the other hand, you want to be able to find all of the User objects that a document was shared with, there are better ways of doing this. You will want a "join table". In your case, the join-table object may be called a Share, and have the following attributes:
class Share
belongs_to :user
belongs_to :document
end
Then, in your Document class,
has_many :shares
has_many :users, :through => :shares
As far as generating the migration, this may be hacky, but you could create a new migration that changes the type to "string" (Edit: correct code):
class AddShareToDocuments < ActiveRecord::Migration
def up
change_column :documents, :share, :string
end
def down
change_column :documents, :share, :array, :default => []
end
end