validate before_destroy

January 12th, 2009

Recently I had to look at various options to do proper validation before destroying a model. Rails doesn't have a validate_before_destroy callback but it does have before_destroy.

We could implement a simple validation before destroy two ways:

Option 1: Implement the callback before_destroy in the model class itself.

Implement the method before_destroy in the model code itself.

1
2
3
4
5
6
7
8

class Organization < ActiveRecord::Base
  def before_destroy
     # Do your thing
     # Return true or false
     self.expired?
  end
end

From the rails documentation

Callbacks are generally run in the order they are defined, with the exception of callbacks defined as methods on the model, which are called last.

So with that said, any associations that are defined in the model would be destroyed before model.destroy call is aborted and there no way of going back.

Option 2: Register the callback before_destroy at the top of the method

In your model code declare at the top

1
2
3
4
5
6
7
8
9
10

class Organization < ActiveRecord::Base
  before_destroy :okToDelete
  protected
  def okToDelete
     # Do your thing
     # Return true or false
     self.expired?
  end
end

In this case, if you define the callback at the very top of the model class (before any other association declaration), then rails makes sure to call this callback first and aborts the destroy call.

You can also pass a block to the callback to keep it simple.

1
2
3
4
5
6
7
8

class Organization < ActiveRecord::Base
  before_destroy do |r|
     # Do your thing
     # Return true or false
     r.expired?
  end
end

or even less

1
2
3
4

class Organization < ActiveRecord::Base
  before_destroy {|r| r.expired?}
end

If you have not upgraded actsas_attachment & still using Sebastin Kanthak's wonderful filecolumn plugin then this is for you.

The plugin uses the unix 'file' command to guess the mime-type of the uploaded file. It uses 'file -bi '. But the latest find command on Leopard, the -b flag has been capitalized. So instead of find -bi you have to do find -Bi.

Use this patch on version 0.3.1 of the file_column release.

I was using the wonderful asset_packager plugin for my project. In addition to the default 'production' env where the merging of .js & .css files I want to test it in my dev, staging env also. It's very easy to turn on merging for more environments.

Just add the following snippet into your config/environment.rb file

Synthesis::AssetPackage.merge_environments = ["stage", "production"]

These are the sessions I am planning to attend in RailsConf this year

If you are like one of me who haven't gone over to the Mac Powerbook Pro camp and started using Textmate then this is for you. I use Eclipse on my Windows Vista Thinkpad and I find it more then enough for my diverse set of projects I work on at one time. It lets me code in java, c++, ruby and I am happy with it as of now.

Enough said. if you haven't heard then here is news for you.. The aptana folks have adopted radrails development and they have a new url for to update your eclipse. Make sure you have eclipse sdk 3.2.2 and update radrails from http://update.aptana.com/update/radrails/3.2/

Recently I had to build ruby 1.8.6 for RHEL 4.4 or CentOS 4.4 for that matter on i386 platform. Download it if it can be of any use to you.

ruby-1.8.6-1.i386.rpm
ruby-devel-1.8.6-1.i386.rpm
ruby-irb-1.8.6-1.i386.rpm
ruby-docs-1.8.6-1.i386.rpm
ruby-libs-1.8.6-1.i386.rpm
ruby-mode-1.8.6-1.i386.rpm
ruby-rdoc-1.8.6-1.i386.rpm
ruby-ri-1.8.6-1.i386.rpm
ruby-tcltk-1.8.6-1.i386.rpm

SORRY FOLKS. Somehow these files are vanished from the host. The links no more work.

Rails 1.2.3

March 13th, 2007

David just tagged rails to 1.2.3 but no formal announcements yet.

http://dev.rubyonrails.org/log/tags/rel_1-2-3

Go ahead and get it for you impatient folks. For me this couldn;t have come at a better time. I can barely wait for the REST fixes and the eTags thingy :)

I had to move a project that was hosted on RubyForge due to two reason:

  1. The project was not open sourced
  2. Client wanted to control where the SVN is hosted.

So all the kudos go to Rubyforge guys who have made wonder-full rss api to dump the tracker data into a XML file and I used this XML file to migrate RF trackers to Trac tickets. I am gonna give the script here which I used for quick and dirty migration. Hopefully it would be useful to you. Warning you: It’s very raw thing..

Here is the script

Railsconf 2007

February 6th, 2007

I just registered for RailsConf2007 and I can’t wait to be there. The last conference I had attended was JavaOne in 2000 but I have never been more excited about attending one. I modified RailConf2006 logo for the one you see in the right.

See you all there.

Google Maps, IE, Polyline

January 25th, 2007

I was capturing mouse double clicks on a google map and was displaying polyline dynamically on based on which icon the user was clicking on. This was working fine in firfox but in IE it was giving me error. I stumbled upon this discussion in google group discussion.

To fix this do this.

  1. Add the line below in your head section
1
2
 
<style type="text/css">v\:* { behavior:url(#default#VML); }</style> 
  1. Change your html line at the top to
1
2
 
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml"> 

Hope this helps.

Google Map Events

January 23rd, 2007

If you are working with google maps then this tool is very handy. This would give you all the events that happens in a google map context.

http://koti.mbnet.fi/ojalesa/exam/events_v2x2.html

One of those can't live without tools.

I needed some basic rich text editing facility on my application. I used the wonderful tiny_mce plugin to integrate tinymce into rails and everything worked fine until I ported the controller to RJS.

In my view .rhtml, the textarea doesn't exist until use clicks a link and then I add a textarea box to the page. This is where thngs get interesting. TinyMCE doesn't recognize the newly added textarea until "explicitly" asked to do so.

Scenerio

  1. User clicks a link which adds textarea to the current page.
  2. User inputs some text in to text area and clicks save.
  3. Input from text area saved and the textarea is removed from the page.

Here is a step by step.

Step1

Define two new JavaScript functions in your public/javascripts/application.js

1
2
3
4
5
6
7
8
9
10
11
 
function initEditor(){
  tinyMCE.idCounter=0;
  tinyMCE.execCommand( 'mceAddControl', true, 'qanda[body]' );
}
// Call triggerSave to collect the input data in the TinyMCE test editor to your plain vanilla textarea
// and remove the control for the text area.
function killEditor() {
  tinyMCE.triggerSave(true,true);
  tinyMCE.execCommand( 'mceRemoveControl', true, 'qanda[body]' );
}

Step 2

In your new_reply.rjs file do this. initEditor is basically telling tinyMCE that the new textarea named 'qanda[body]' needs to be rich edited.

1
2
 
page.call 'initEditor'

Step 3

The newly created form which has the textarea field in it needs to be coded like this.

1
2
3
4
5
6
7
8
9
10
 
<% form_remote_for :qanda,
                    reply,
                    :loading => 'Content.disableContentForm()',
                    :url => {:action => 'reply'},
                    :html => { :id => 'content-form', :onsubmit => 'killEditor();' } do |f| %>
    <%= %Q!<input id="submit_id" name="submit_id" type="hidden" value="12345">! %>
    <%= submit_tag 'Post Reply', :name => 'reply', :value => 'reply' %>
    <%= submit_tag 'Cancel', :name => 'cancel', :value => 'cancel' %>
<% end %>

Your code doesn't have to be exactly like that but pay particular attention to

1
2
 
:onsubmit => 'killEditor();'

which is basically calling the defined javascript function killEditor() defined in step1.

Moving to Mephisto

December 11th, 2006

At long last http://ajay.ws moved to Mephisto. I have been putting off this for too long and finally I had the time to do it. The joy of Rails and ability to tinker with Rails code instead of PHP made me move from Wordpress to Mephisto.

I have been digging around the ActionMailer code to see how I can customize the subject line on all mine outgoing emails. I have many different rails environment and I would like to somehow distinguish between my production emails and other environment emails.

I have been thinking all fancy to do this without monkey patching the rails code and finally figured out how easy it is in rails. I really didn’t have to do anything other then defining an accessor method for the attribute ‘subject’ in my notifier model which would override the default accessor implementation of ActionMailer.

1
2
3
4
5
6
7
8
9
10
11
12
13
 
class Notifier < ActionMailer::Base
  def subject
    case ENV['RAILS_ENV']
    when 'production' : @subject
    else "[#{ENV['RAILS_ENV']}]-#{@subject}"
  end

  def notify_dead
    @subject = 'You are dead'
    .....
  end
end
This works all dandy.

fcgi_watch: Run Not Walk

October 1st, 2006

If you are using Rails in a shared hosting environment and use fastcgi then Run and Read this Post by Al Evans. It’s a awesome utility to keep a watch on the fcgi processes and cleans them up if need to. I call this script from crontab regularly to cleanup.

Nonprofit_banner_horizontal_banner_3991