Friday 18 January 2013

Using find_or_create_by in Rails

Find by one attribute


   User.find_or_create_by_username('beena')

      It will find the record with username 'beena' in table user and if record is not found then it will create a new record with username 'beena'

Find by one attribute or create by multiple attributes


   User.find_or_create_by_username('beenas',
                :first_name => 'beena', 
                :last_name => 'shetty', 
                :role_id => 1)



Find by multiple attributes


   User.find_or_create_by_username_and_role_id('beenas', 2)

      It will find the record with username 'beena' and role_id '2' in table user and if record is not found then it will create a new record with username 'beena' and role_id 2

Find by multiple attributes and pass multiple attribute to a new row to be created


 User.find_or_create_by_username_and_role_id('beenas', 2) do |u|
                u.first_name => 'beena', 
                u.last_name => 'shetty', 
                u.role_id => 1
 end

      It will find the record with username 'beena' and role_id '2' in table user and if record is not found then it will create a new record with username 'beena', role_id 2 and along with other attribute passed.

No comments:

Post a Comment