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.

1 comment:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Front end developer learn from Javascript Training in Chennai . or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry. ES6 Training in Chennai

    ReplyDelete