Adding a Hash to an ActiveRecord Hash - ruby

I read How to add a Hash object to an ActiveRecord class? Tried but migration fails and followed the format there.
I tried:
class AddTestResponsesToSurveys < ActiveRecord::Migration
def change
add_column :surveys, :responses, :hash
end
end
When I run rake db:migrate, I get an error in my schema.rb file that says:
# Could not dump table "surveys" because of following StandardError
# Unknown type 'hash' for column 'responses'
What am I doing wrong?

generate migration with column type text
class AddTestResponsesToSurveys < ActiveRecord::Migration
def change
add_column :surveys, :responses, :text
end
end
And in your Survey model, add this
serialize :responses, Hash

Related

Rails 3 NoMethodError (undefined method `unserialized_value' for "--- []\n":String):

I am using Rails 3.2.13 and postgress.
I am getting below error only in production server
NoMethodError (undefined method `unserialized_value' for "--- []\n":String):
app/controllers/blogs_controller.rb:159:in `content_generators'
I am serializing Array to store it in db. Below is code.
Controller
class BlogsController < ApplicationController
def content_generators
#blog = Blog.find(params[:id])
#users = #blog.content_generators.map do |id|
User.find(id)
end
end
end
Model
class Blog < ActiveRecord::Base
serialize :post_access, Array
serialize :content_generators, Array
attr_accessible :post_access, :content_generators
end
Migration
class AddContentgeneratorsToBlog < ActiveRecord::Migration
def change
add_column :blogs, :content_generators, :string, :default => [].to_yaml
end
end
I have already used serialization. You can see post_access is serialized. And that works perfect.
But now when I added another column content_generators it starts breaking.
Thanks for your help in advance.
Since you are using postgresql I strongly recommend using the built in array functionality:
# Gemfile
gem 'postgres_ext'
class MyMigration
def change
add_column :my_table, :that_array_column, :text, array: true, default: []
end
end
Then remove the serialize calls in your model and that's it. PG serialized array's behave exactly the same as YAML serialized ones on the model, except the db supports some query methods on them.

Create a migration to add the `admin` field to the `users` table

How to create migration to add the admin field to the users table with a boolean value and set default to false in Sinatra? I am using Active Record.
It's still just ActiveRecord, this would be no different than using it in Rails.
class AddAdminToUsers < ActiveRecord::Migration
def change
add_column :admin, :boolean, :default => false
end
end
You may also want to check out the sinatra-activerecord gem which will give you some extra rake tasks and makes things a little easier.
Here is also a useful article on using Sinatra with ActiveRecord.
Sinatra and ActiveRecord
I was having this problem too.
I solved it using change_table method instead of add_column so final code would look like:
class AddAdminToUsers < ActiveRecord::Migration
def change
change_table :users do |t|
t.column :admin, :boolean, default: false
end
end
end

Agile Web Development on Rails. 10.4 -undefined method `price' for nil:NilClass

I am stuck here and it seems that there is no answer anywhere online. The exercise says:
Create a migration that copies the product price into the line item, and change the add_product method in the Cart model to capture the price whenever a new line item is created.
My code:
class AddPriceToLineItem < ActiveRecord::Migration
def self.up
add_column :line_items, :price, :decimal
say_with_time "Updating prices..." do
LineItem.find(:all).each do |li|
li.update_attribute :price, li.product.price
end
end
end
def self.down
remove_column :line_items, :price
end
end
I also tried:
class AddPriceToLineItem < ActiveRecord::Migration
def self.up
add_column :line_items, :price, :decimal
LineItem.all.each do |li|
li.price = li.product.price
end
end
def self.down
remove_column :line_items, :price
end
end
I keep getting this error:
rake db:migrate
== AddPriceToLineItem: migrating =============================================
-- add_column(:line_items, :price, :decimal)
-> 0.0010s
-- Updating prices...
rake aborted!
An error has occurred, this and all later migrations canceled:
undefined method `price' for nil:NilClass
It is weird that it is saying undefined nil:nilClass, as price has just been defined in the line before.
Im using rails (3.2.1), ruby 1.9.3p125.
Anyone can help?
This errors means that you are calling price on something that is nil. So I'm pretty sure one of your LineItem does not have a product.
I would be more particular. In my case a had a cart_id and product_id were nil.
So I simple clean up the DB by
sqlite> DELETE FROM line_items WHERE id= bad_id";

How can I create a field using the id from the same row in ActiveRecord Ruby

-----UPDATE-----
Well, seems that the problem was in last.id. When database is created works OK, but when not fails. Now the question is different: How can I create a field using the id from the same row?
--------ORIGINAL------
I'm working with active record in pure ruby (without Rails), and I'm literally getting crazy with this.
This is my code
class Enviroment < ActiveRecord::Base
#self.table_name = 'enviroments'
self.connection.create_table(:enviroments, :force=>true) do |t|
t.column :name, :string, :default=>'env-'+ (last.id-1).to_s
t.column :ssh, :string, :default=>nil
end
end
and here the error:
ActiveRecord::StatementInvalid: Could not find table 'enviroments'
from /usr/lib/ruby/gems/1.8/gems/activerecord-3.2.3/lib/active_record/connection_adapters/sqlite_adapter.rb:465:in `table_structure'
if I useself.table_name = 'enviroments' still not working. I've updated the gems and neither.
I'm newbie with ruby and databases, but I can't understand this problem, I think this same code worked in the past :S
Your code to create the table (very odd to have that in the model by the way) is calling last.id, and of course to call last the table must already exist.
Because you're passing :force => true to create_table you'll actually destroy the table if it already exists.
You could probably make your code work if you stashed the value of last.id in a local variable before the call to create_table but I don't understand why you are creating tables like this.
Finally, this was my solution:
class Enviroment < ActiveRecord::Base
after_create :create_default
private
def create_default
if name == nil
s = 'env-' + self.id.to_s
self.name = s
self.save
end
end
end
class CreateSchema < ActiveRecord::Migration
create_table(:enviroments, :force=>true) do |t|
t.column :name, :string, :default=>nil
t.column :ssh, :string, :default=>nil
end

does a sequel models generator exists?

I'm looking for a ruby class that could generate the sequel model file for Ramaze after reading the definition of the table in a mySQL database.
For example, I would like to type :
ruby mySuperGenerator.rb "mytable"
And the result shold be the file "mytable.rb" in "model" directory, containing :
class Mytable < Sequel::Model(:mytable)
# All plugins I've defined somewhere before lauching the generator
plugin :validation_helpers
plugin :json_serializer
one_to_many :othertable
many_to_one :othertable2
def validate
# Generating this if there are some not null attributes in this table
validates_presence [:fieldthatshoulnotbenull1, :fieldthatshoulnotbenull2]
errors.add(:fieldthatshoulnotbenull1, 'The field fieldthatshoulnotbenull1 should not be null.') if self.fieldthatshoulnotbenull1.nil?
end
def before_create
# All the default values found for each table attributes
self.creation_time ||= Time.now
end
def before_destroy
# referential integrity
self.othertable_dataset.destroy unless self.othertable.nil?
end
end
Does someone knows if such a generator exists ?
Well...
I finally wrote my script.
see https://github.com/Pilooz/sequel_model_generator Have look and fork !

Resources