Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Finding or Building a New Object In Rails Through Active Records

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 356
    Comment on it

    Finding or Building a New Object In Rails Through Active Records

    Active records provide us with some methods which we can use in our database

    to find or create objects automatically without having to fire two queries.

    These methods run 2 queries through a single method as fallows :

    • find_or_create_by

    This method checks in the table if the record with that attribute is there in the table or not. If it finds the record with

    that attribute it fetches the record and returns it back to us but if the record is not there in the table then it 

    creates the record.

    User.find_or_create_by(name: 'Tom Cruise')

     find or create by method returns either the record that already exists or the new record.

    • find_or_create_by!

    This method is used to raise an exception if the new record being created is invalid. For example if we have passed a validation to the record that 

    validates :city, presence: true

    and then if we try to create a record without passing in the city, then it will raise an exception.

    for example if we do this

    User.find_or_create_by!(name: 'Tom Cruise', city: "NewYork")

    so it will create a record successfully or else it will raise an exception.

    • find_or_initialize_by

    This method is almost same as find_or_create_by method but it will call the new method instead of create method. That means it wont directly save the record in the database. First it will create an instance of the new record in a variable and then the we run the .save method on the variable to save the record in the table.

    user = User.find_or_initialize_by(name: "Tom Cruise")
    user.save

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: