Rails: getting multiple selected values from selection box

I got stuck for last half an hour at ‘getting the values of multiple selected items in a muliple selection box’ using Ruby/Rails. Got it after hard ‘googling’ and got the solution here.

When trying to get multiple selected values from a <SELECT> tag into @params, call your parameter something with [] on the end. That way rails knows it’s multiple.

So instead of

<select name="job[techs]" size="5" multiple="multiple">

Use:

<select name="job[techs][]" size="5" multiple="multiple">

Thanks google and Ruby/Rails community !

Advertisements

sending mails using ruby

There is a very common requirement especially in web services, that of sending notification email for some action say, addition/deletion/updation of database in user signup or product selection in a shopping cart. Ruby handles it beautifully. This is obvious. What is not obvious is that it actually gives user different ways of implementing it.

  • RubyMail
  • TMail
  • ActionMailer (uses TMail)

I used ActionMailer. I had a database driven website. I wanted to notify administrator for any updation in the database (addition/edition of records). So this is how I did it :-

ruby script/generate mailer Notifier

This creates a file in several files :-


test/unit/notifier_test.rb
test/fixtures/notifier
app/models/notifier.rb
app/views/notifier

Of Particular interest is file :- app/models/notifier.rb. Add following method in this file in the class Notifier,


def notifyMyAction( argument )
  # Email header info MUST be added here
  @recipients = "xyz@abc.com, mno@def.com"
  @from = "intelligent@ruby.com"
  @subject = “Action happened” 

  # Email body substitutions go here
  @body[“argument”] = argument
end

And following code in the controller’s method where you want to notify.


def update_db_and_notify
...
  Notifier::deliver_notifyMyAction((arg)
...
end

NOTE: ‘deliver_’ before the function name !!

Now put the mail body as you would like to put, in the view/notifier/notifyMyAction.rhtml


Dear  <%= @argument >, 

Your database just got updated !! 

Thanks
-Notifier

We are just done. Finally, append following text to the config/environment.rb file (if not already there)
and change address to _your_ mail server address. domain is optional but should make senses since some spam filters filter out the mails on the basis of this. username and password are also optional as is the last one which i commented in my case 🙂


ActionMailer::Base.server_settings = {
  :address  => "mail.server.com",
  :port  => 25,
  :domain  => 'www.abc.com',
  :user_name  => "me@abc.com",
  :password  => ‘mypass’,
#  :authentication  => :login
    }

There is more to learn like attachments, HTML messages, and many other tweaks. You can get it here.

Hail ruby !