Working with open source technologies

Sunday, December 5, 2010

Implementing Nested attributes

Nested attributes is a life saver for the developers who wants to save the data in 2-3 different tables on submitting a single form.


For example,
You are creating a profile page where user can enter multiple locations. So for that create 2 models Profile and Locations.

In app/models/profile.rb

class Profile < ActiveRecord::Base
has_many :locations, :dependent => :destroy
accepts_nested_attributes_for :locations, :allow_destroy => true
end

class Location < ActiveRecord::Base
belongs_to :profile
# In this model you can add validations like
validates_format_of :phone_number
end

Now, "accepts_nested_attributes_for" is very important. If you missed it then it will give you Error "nil.errors" when you will try to run the application.

In the profile controller you have to right
class ProfilesController < ApplicationController
def new
@profile.locations.build #(You can add the condition if you dont want to build the location object everytime)
end

def create
@profile = Profile.new(params[:profile])
@profile.save
end
end

In app/views/profiles/new.html.erb

<% form_for :profile, @profile, :url => profile_path(params[:id]), :method => :post do |f| %>
<%= f.text_field :name %>
<% f.fields_for :locations do |location| %>
<%= render "location_fields", :f => location %>
<% end %>
# if you want the user to add the locations dynamically then add this line

<%= link_to_add_fields "Add Location", f, :locations %>

<%= link_to_remove_fields "Remove Location", f %>< /p>

<% end %>


In Application helper add this two methods to add and remove the fields(partials) dynamically

module ApplicationHelper
def link_to_remove_fields(name, f)
f.hidden_field(:_destroy) + link_to_function(name, "remove_fields(this)")
end

def link_to_add_fields(name, f, association)

new_object = f.object.class.reflect_on_association(association).klass.new
fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder|
render(association.to_s.singularize + "_fields", :f => builder)

end


link_to_function(name, h("add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")"))
end
end

Create a js file and put these methods in that file
function remove_fields(link) {
$(link).prev("input[type=hidden]").val("1");
$(link).closest(".fields").hide();
}

function add_fields(link, association, content) {
var new_id = new Date().getTime();
var regexp = new RegExp("new_" + association, "g")
$(link).parent().before(content.replace(regexp, new_id));


Now when you Click on "Add location" then actually the helper method render the partial on the view page. When it render the page it creates a unique id it identify the locations fields.
So when you submit the form you will see the parameters as

params : { :profile => {:name => nil, :location_attributes => {"0" => {"address" => "ABC", "_delete" => ""}, "123456789" => {"address" => "XYZ", "_delete" => ""} }}}

This means user has added two locations in the profile.

Now when user click on "Remove Location" then through javascript we set the "_delete" field to "1". So the nested_attributes will remove the relevant record from the database.
The parameters will go as :

params : { :profile => {:name => nil, :location_attributes => {"0" => {"address" => "ABC", "_delete" => ""}, "123456789" => {"address" => "XYZ", "_delete" => "1"} }}}

Also if you inspect the "Add Location" button carefully you will see that the partial is already rendered in the view, but when you click on that button the partial is visible to the user.
If you want to have access to the random number which generated at runtime e.g "123456789" then in the partial you just have to right "new_locations" i.e. "new_#{table_name}"




Thursday, February 11, 2010

MIME types for Microsoft office 2007 & 2003

MIME content-types supported by most web servers, identified with file extensions, are listed in the following table.

.docm,application/vnd.ms-word.document.macroEnabled.12
.docx,application/vnd.openxmlformats-officedocument.wordprocessingml.document
.dotm,application/vnd.ms-word.template.macroEnabled.12
.dotx,application/vnd.openxmlformats-officedocument.wordprocessingml.template
.potm,application/vnd.ms-powerpoint.template.macroEnabled.12
.potx,application/vnd.openxmlformats-officedocument.presentationml.template
.ppam,application/vnd.ms-powerpoint.addin.macroEnabled.12
.ppsm,application/vnd.ms-powerpoint.slideshow.macroEnabled.12
.ppsx,application/vnd.openxmlformats-officedocument.presentationml.slideshow
.pptm,application/vnd.ms-powerpoint.presentation.macroEnabled.12
.pptx,application/vnd.openxmlformats-officedocument.presentationml.presentation
.xlam,application/vnd.ms-excel.addin.macroEnabled.12
.xlsb,application/vnd.ms-excel.sheet.binary.macroEnabled.12
.xlsm,application/vnd.ms-excel.sheet.macroEnabled.12
.xlsx,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.xltm,application/vnd.ms-excel.template.macroEnabled.12
.xltx,application/vnd.openxmlformats-officedocument.spreadsheetml.template


MIME TypeIdentificationFile Extension
application/acadAutoCADdwg
application/arjcompressed archivearj
application/astoundAstoundasd, asn
application/clariscadClarisCADccad
application/draftingMATRA Prelude draftingdrw
application/dxfDXF (AutoCAD)dxf
application/i-deasSDRC I-DEASunv
application/igesIGES graphics formatiges, igs
application/java-archiveJava archivejar
application/mac-binhex40Macintosh binary BinHex 4.0hqx
application/msaccessMicrosoft Accessmdb
application/vnd.ms-excelMicrosoft Excelxla, xls, xlt, xlw
application/vnd.ms-powerpointMicrosoft PowerPointpot, pps, ppt
application/msprojectMicrosoft Projectmpp
application/mswordMicrosoft Worddoc, word, w6w
application/mswriteMicrosoft Writewri
application/octet-streamuninterpreted binarybin
application/odaODAoda
application/pdfAdobe Acrobatpdf
application/postscriptPostScriptai, eps, ps
application/pro_engPTC Pro/ENGINEERpart, prt
application/rtfRich Text Formatrtf
application/setSET (French CAD)set
application/slastereolithographystl
application/solidsMATRA Prelude Solidssol
application/STEPISO-10303 STEP datast, step, stp
application/vdaVDA-FS Surface datavda
application/x-bcpiobinary CPIObcpio
application/x-cpioPOSIX CPIOcpio
application/x-cshC-shell scriptcsh
application/x-directorMacromedia Directordcr, dir, dxr
application/x-dviTeX DVIdvi
application/x-dwfAutoCADdwf
application/x-gtarGNU targtar
application/x-gzipGNU ZIPgz, gzip
application/x-hdfNCSA HDF Data Filehdf
application/x-javascriptJavaScriptjs
application/x-latexLaTeX sourcelatex
application/x-macbinaryMacintosh compressedbin
application/x-midiMIDImid
application/x-mifFrameMaker MIFmif
application/x-netcdfUnidata netCDFcdf, nc
application/x-shBourne shell scriptsh
application/x-sharshell archiveshar
application/x-shockwave-flashMacromedia Shockwaveswf
application/x-stuffitStuffIt archivesit
application/x-sv4cpioSVR4 CPIOsv4cpio
application/x-sv4crcSVR4 CPIO with CRCsv4crc
application/x-tar4.3BSD tar formattar
application/x-tclTCL scripttcl
application/x-texTeX sourcetex
application/x-texinfoTexinfo (Emacs)texi, texinfo
application/x-troffTroffroff, t, tr
application/x-troff-manTroff with MAN macrosman
application/x-troff-meTroff with ME macrosme
application/x-troff-msTroff with MS macrosms
application/x-ustarPOSIX tar formatustar
application/x-wais-sourceWAIS sourcesrc
application/x-winhelpMicrosoft Windows helphlp
application/zipZIP archivezip
audio/basicBASIC audio (u-law)au, snd
audio/midiMIDImid, midi
audio/x-aiffAIFF audioaif, aifc, aiff
audio/x-mpegMPEG audiomp3
audio/x-pn-realaudioRealAudiora, ram
audio/x-pn-realaudio-pluginRealAudio plug-inrpm
audio/x-voiceVoicevoc
audio/x-wavMicrosoft Windows WAVE audiowav
image/bmpBitmapbmp
image/gifGIF imagegif
image/iefImage Exchange Formatief
image/jpegJPEG imagejpe, jpeg, jpg
image/pictMacintosh PICTpict
image/pngPortable Network Graphicpng
image/tiffTIFF imagetif, tiff
image/x-cmu-rasterCMU rasterras
image/x-portable-anymapPBM Anymap formatpnm
image/x-portable-bitmapPBM Bitmap formatpbm
image/x-portable-graymapPBM Graymap formatpgm
image/x-portable-pixmapPBM Pixmap formatppm
image/x-rgbRGB imagergb
image/x-xbitmapX Bitmapxbm
image/x-xpixmapX Pixmapxpm
image/x-xwindowdumpX Window System dumpxwd
multipart/x-gzipGNU ZIP archivegzip
multipart/x-zipPKZIP archivezip
text/htmlHTMLhtm, html
text/plainplain textC, cc, h, txt
text/richtextMIME Richtextrtx
text/tab-separated-valuestext with tabstsv
text/x-setextStructurally Enhanced Textetx
text/x-sgmlSGMLsgm, sgml
video/mpegMPEG videompe, mpeg, mpg
video/msvideoMicrosoft Windows videoavi
video/quicktimeQuickTime videomov, qt
video/vdoVDO streaming videovdo
video/vivoVIVO streaming videoviv, vivo
video/x-sgi-movieSGI Movieplayer formatmovie
x-conference/x-cooltalkCoolTalkice
x-world/x-svrVirtual realitysvr
x-world/x-vrmlVRML Worldswrl
x-world/x-vrtVirtual realityvrt

Thursday, January 21, 2010

Add a branch to git repository

> git clone [git url]

By default the branch is master
> git branch
* master

create a branch with the current repository
> git branch publish

check the new created branch by
> git branch
* master
publish

Change the default repository
> git checkout publish

Now you can see the Head is pointing to the publish branch
> git branch
master
* publish

Now change something in the repository or add any file and the
> git push master publish

To see the difference Do
> git checkout master

Whatever changes you have made in the previous check-in will not be reflected in the current repository

Followers