Tuesday, July 7, 2009

Rails 2.3 Model Nested Form

http://railscasts.com/episodes/73-complex-forms-part-1

http://railscasts.com/episodes/74-complex-forms-part-2

http://railscasts.com/episodes/75-complex-forms-part-3

Ryan made a great introduction about having a form dealing with multiple models. Yet in Rails 2.3 due to popular demand, it is already bundled with this feature.

http://weblog.rubyonrails.org/2009/1/26/nested-model-forms

http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes

http://stackoverflow.com/questions/818460/problems-with-nested-form-fields-showing-up

First of all, the model has to know about the nested attributes. With that the course can access the sections_attributes.
class Course < ActiveRecord::Base
has_many :sections

accepts_nested_attributes_for :sections

end

Then for the view at new.html.erb
<% form_for @course do |course_form| %>

<%= course_form.label :title %>
<%= course_form.text_field :title %>

<% course_form.fields_for :sections do |section_form| %>

<%= section_form.label :sec %>
<%= section_form.text_field :sec %>

<% end %>

<%= submit_tag %>
<% end %>

In the controller, there is a need to add @course.sections.build at the new action in order to populate the form and create the section together with the course in a hash.
def new
@course = Course.new
@course.sections.build
end

But, wait there is more... you might wanna add more sections dynamically... and i found a tutorial that just do that

http://railsforum.com/viewtopic.php?id=28447

Thursday, July 2, 2009

Sending Email on Rails via Gmail

If you need to send an email via Gmail on a Rails application ( and if you are running Rails >= 2.2.1 with Ruby 1.8.6 )

1) Register a gmail account

2) Install the ActionMailer_tls gem from http://github.com/openrain/action_mailer_tls/tree/master

3) Follow the instruction on the readme of the Gem,

  • To install the gem (the preferred way):1. `sudo gem install openrain-action_mailer_tls -s http://gems.github.com`
    2. `./script/generate action_mailer_tls`
    3. Copy RAILS_ROOT/config/smtp_gmail.yml.sample to RAILS_ROOT/config/smtp_gmail.yml
    4. Update the configuration file with your settings by keying in your gmail username and password on smtp_gmail.yml


Make sure the username includes @gmail.com in the smtp_gmail.yml file
:user_name: testing123@gmail.com
:password: thisisatestpassword

And you are good to go, in order to test if the mail is actually sent, follow the testing instruction in the README.

Thanks to http://www.justinball.com/2009/06/25/sending-email-with-ruby-on-rails-2-3-2-and-gmail/