Skip to main content

Posts

Showing posts from 2013

Validating Nested Models

What is validation ? Validations are required for ensuring that the received data is correct and valid. If the received data is valid then we do the further processing with the data. Nested Model Validation Nested model is sometimes tricky when you have complex associations. Here I'm explaining how we can do nested model validation. We use nested form to save associations through its parent model. Generally we do: class Album < ActiveRecord::Base   has_many :songs   accepts_nested_attributes_for :songs end When we are using nested form we want to save a new or edit an existing album with songs. Now suppose we want all the songs to be removed on removal of the album. class Album < ActiveRecord::Base   has_many :songs   accepts_nested_attributes_for :songs, :allow_destroy => true end At this point we can detect and reject empty association entries class Album < ActiveRecord::Base   has_many :songs   accepts_n

Nested Form In Rails 3

What is "Nested form In Rails 3" and when do we use it? This is a Rails gem for conveniently manage multiple nested models in a single form. It does so in an unobtrusive way through jQuery or Prototype. Example :- Suppose we have two models " Profile " and " Picture ". We want to get all the information in the same form. In this case we got to use "Nested Form". What are the steps to setup nested form gem in your app? Add it to your Gemfile (by writing  gem "nested_form"  to you Gemfile) then run bundle to install it . Asset Pipeline Setup And then add it to the Asset Pipeline in the application.js file: //= require jquery_nested_form and don't forget to do $ bundle install Non Asset Pipeline Setup If you do not use the asset pipeline, run this generator to create the JavaScript file. rails g nested_form:install You can then include the generated JavaScript in your layout. <%= javascript_include_tag :d