Ruby on Rails

Depends how you interpret things

Tag Archives: rails

Enhancing script/console

I Used Rails ./script/console a lot for debugging my rails apps. Every time when I started debugging something, I have to keep my console log[*.log] file to see what corresponding queries being generated to carried out the result I desired.

I found a better solution for that. I enhanced my script/console, which enabled on-screen query logging for my rails app. I made a small change to #{RAILS_ROOT}/script/console.rb file, which it will look to load any additional ruby file resides in #{RAILS_ROOT}/console_script/ if available.

I have also included the script I wanted to load in the first place, I find it quite handy to be able to see what kind of queries my commands are generating.

#updates /script/console.rb

LOAD_HOOK_DIRECTORY = “#{RAILS_ROOT}/console_scripts”

Find.find( LOAD_HOOK_DIRECTORY ) do |filename|
if filename =~ /\.rb$/
puts “Adding #{filename} to load-path”
libs << ” -r #{filename}”
end
end
#add sql_log.rb file to /console_script/
def log_to(stream=STDOUT, colorize=true)
ActiveRecord::Base.logger = Logger.new(stream)
ActiveRecord::Base.clear_active_connections!
ActiveRecord::Base.colorize_logging = colorize
end
log_to
Advertisements

Rails ActiveRecord – has_and_belongs_to_many & Duplicate entry Error

Scenario :

In One of my project, we had  Many to Many association between models. this allowed me to look more deeply into the has_and_belongs_to_many(HABTM)  association.

When we say:

class Movies < ActiveRecord::Base
has_and_belongs_to_many :gallery_photos, :join_table=> "movies_gallery_photos"
end

class GalleryPhoto < ActiveRecord::Base
has_and_belongs_to_many :movies, :join_table=>"movies_gallery_photos"
end

Rails will assume there is a table “movies_gallery_photos” that include foreign keys to the two entities. So this table should be created by the following migration

create_table :movies_gallery_photos, :id => false do |t|
t.integer :movie_id, :null => false
t.integer :gallery_photo_id, :null => false
end

:id=>false will prevent the creation of the default primary key for that table.

as the API documentation say; other attributes in that relation will be loaded with the objects and will be read only, including the :id. So failing to disable the id generation for that table will cause the loaded objects to have and “id” attribute holding the value of the id or the movies_gallery_photos entries instead of the ids of the target entity (movies or gallery_photos here).

Issue :

Having (:id) false helps to over Mysql::Error: Duplicate entry ‘#’ for key #” entry error we faces while adding entries. (movie.gallery_photos << photo). But it leads to creation and availability of duplicate values in the movies_gallery_photos table. i.e.

movies.gallery_photos << photos

will not check for uniqueness of the photos objects.