Translate

Tuesday, 9 July 2024

Understanding the Differences: update, update_columns, update_column, update_attributes, assign_attributes in Rails


In Rails, the methods update, update_columns, update_column, update_attributes,
and assign_attributes may sound similar but have distinct differences.
Some methods directly update the record in the database,
while others only set attributes without sending a query.

Here’s a detailed breakdown:

update(id, attributes) (public)

The update method updates one or more objects and saves them to the database
if validations pass.
The resulting object is returned regardless of whether the object was saved
successfully or not.

Parameters:
id: The ID or an array of IDs to be updated.
attributes: A hash of attributes to set on the object, or an array of hashes.

Examples:
# Updating one record:
Person.update(15, user_name: 'Samuel', group: 'expert')
# Updating multiple records:
people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy" } }
Person.update(people.keys, people.values)

update_columns(attributes) (public)

The update_columns method updates the attributes directly in the database using
an UPDATE SQL statement.
It bypasses regular update procedures, making it the fastest way to update attributes.
However, it comes with several caveats:

Validations are skipped.
Callbacks are skipped.
updated_at/updated_on are not updated.
This method raises an ActiveRecord::ActiveRecordError if called on new objects or
if any of the attributes are marked as read-only.

Example:
user.update_columns(last_request_at: Time.current)

update_column(name, value) (public)

The update_column method is equivalent to update_columns(name => value).
It directly updates a single attribute in the database.

update_attributes(attributes) (public)

The update_attributes method updates all attributes from the passed-in hash
and saves the record. If the object is invalid, the save will fail and false
will be returned.

assign_attributes(new_attributes, options = {}) (public)

The assign_attributes method allows you to set all attributes for a particular
mass-assignment security role by passing in a hash of attributes with keys
matching the attribute names (which match the column names) and the role name
using the :as option. To bypass mass-assignment security,
use the :without_protection => true option.

Examples:
class User < ActiveRecord::Base
attr_accessible :name
attr_accessible :name, :is_admin, as: :admin
end

user = User.new
user.assign_attributes({ name: 'Josh', is_admin: true })
user.name # => "Josh"
user.is_admin? # => false

user = User.new
user.assign_attributes({ name: 'Josh', is_admin: true }, as: :admin)
user.name # => "Josh"
user.is_admin? # => true

user = User.new
user.assign_attributes({ name: 'Josh', is_admin: true }, without_protection: true)
user.name # => "Josh"
user.is_admin? # => true

Source: apidock.com/rails/ActiveRecord
By understanding these differences, you can choose the appropriate
method for your needs and ensure your Rails applications are both efficient and secure.


Sunday, 20 August 2023

Explain About Restful Architecture?

 RESTful architecture, also known as REST (Representational State Transfer), is a design principle and architectural style commonly used in web development to design networked applications, particularly web services and APIs. It provides a set of guidelines for creating well-organized, scalable, and maintainable web applications that follow a client-server interaction pattern. REST is based on a few key principles that promote simplicity, scalability, and modularity.


Key principles of RESTful architecture:


1. **Client-Server Separation:** REST separates the client (user interface) and the server (data storage and processing), allowing each to evolve independently. This separation improves scalability and flexibility.


2. **Stateless Communication:** Each request from the client to the server must contain all the information necessary for the server to fulfill the request. The server doesn't store any client state between requests. This simplifies server design and enhances scalability.


3. **Resource-Based Identification:** Resources are the main entities in a RESTful architecture, and each resource is identified by a unique URL (Uniform Resource Locator). Resources represent data or services that can be accessed, manipulated, or modified through the API.


4. **HTTP Methods:** RESTful APIs use standard HTTP methods (GET, POST, PUT, DELETE, etc.) to perform operations on resources. Each HTTP method corresponds to a specific action on the resource (e.g., GET for reading, POST for creating, PUT for updating, DELETE for deleting).


5. **Uniform Interface:** REST enforces a uniform interface across different resources and applications. This consistency simplifies communication and allows clients and servers to evolve independently.


6. **Resource Representation:** Resources can have multiple representations, such as JSON, XML, HTML, or other formats. Clients and servers can negotiate the preferred representation using the `Accept` and `Content-Type` headers.


7. **HATEOAS (Hypermedia as the Engine of Application State):** This principle suggests that a client can navigate the application's resources using hyperlinks provided in the responses. This reduces the coupling between the client and server, as the client can discover available actions dynamically.


Benefits of RESTful architecture:


- **Simplicity:** RESTful APIs are straightforward and easy to understand due to their consistent use of HTTP methods and resource-based URLs.

- **Scalability:** Stateless communication and separation of concerns allow for efficient scaling of both clients and servers.

- **Flexibility:** Clients and servers can evolve independently, allowing updates without breaking existing clients.

- **Interoperability:** RESTful APIs can be consumed by a variety of clients, including web browsers, mobile apps, and other services.

- **Caching:** HTTP's caching mechanisms can be leveraged to improve performance and reduce server load.

- **Standardization:** REST follows established HTTP standards, making it widely supported and easy to integrate with various tools.


In summary, RESTful architecture provides a set of principles for designing web applications that promote simplicity, scalability, and modularity. It emphasizes resource-based URLs, standard HTTP methods, stateless communication, and a uniform interface, making it a popular choice for building web services and APIs.

Saturday, 19 August 2023

Difference between map and each, give one example for same output

 In Ruby, both `map` and `each` are used to iterate over collections, but they have different purposes and behaviors.


1. **`each`:**

   The `each` method is an iterator that allows you to loop through each element of a collection and perform an action with each element. However, `each` doesn't transform or modify the original collection; it's mainly used for its side effects.


   ```ruby

   numbers = [1, 2, 3, 4, 5]

   numbers.each do |num|

     puts num * 2

   end

   ```


   In this example, the `each` loop doubles each element in the `numbers` array and prints the result. The original array remains unchanged.


2. **`map`:**

   The `map` method is also an iterator, but it creates a new array by applying a block of code to each element of the original collection. It's used to transform the elements and return a new array.


   ```ruby

   numbers = [1, 2, 3, 4, 5]

   doubled_numbers = numbers.map do |num|

     num * 2

   end

   ```


   In this example, the `map` method doubles each element in the `numbers` array and returns a new array called `doubled_numbers`. The original array remains unchanged.


Here's an example that demonstrates the difference between `each` and `map` using the same output:


```ruby

numbers = [1, 2, 3, 4, 5]


# Using 'each' to print doubled values

numbers.each do |num|

  puts num * 2

end


# Using 'map' to create a new array with doubled values

doubled_numbers = numbers.map do |num|

  num * 2

end


puts doubled_numbers.inspect

```


In this example, both the `each` loop and the `map` method produce the same output (doubled values of the original numbers), but the key difference is that `each` only performs an action (printing), while `map` transforms the data and creates a new array.

Sunday, 5 March 2023

Here is a 30-day plan to help you prepare for a Ruby on Rails interview:

Week 1:


Day 1-2: Refresh your knowledge of Ruby programming language fundamentals, including object-oriented programming concepts, data types, control flow, and loops.


Day 3-4: Review the basics of Ruby on Rails, including the Model-View-Controller (MVC) architecture, ActiveRecord, routing, and testing.

Day 5-6: Dive deeper into ActiveRecord and learn how to create relationships between models, use callbacks, and handle validations.

Day 7: Take a break and relax.

Week 2:

Day 8-9: Learn about advanced topics in Rails, such as caching, performance optimization, and security.

Day 10-11: Study common design patterns used in Rails applications, such as Decorator, Service Objects, and Presenters.

Day 12-13: Practice building CRUD operations and implementing authentication and authorization.

Day 14: Take a break and relax.

Week 3:

Day 15-16: Learn about front-end development tools and frameworks that are commonly used with Rails, such as Webpacker, React, and Vue.js.

Day 17-18: Study advanced topics in Rails development, such as GraphQL and API-only applications.

Day 19-20: Review common interview questions for Ruby on Rails developers and practice your answers.

Day 21: Take a break and relax.

Week 4:

Day 22-23: Research the company you are interviewing with and learn about its products, culture, and mission.

Day 24-25: Build a portfolio of your previous work, showcasing your best projects and highlighting your contributions.

Day 26-27: Practice explaining technical concepts in a clear and concise manner to non-technical people.

Day 28-29: Do mock interviews with friends or family members to practice answering interview questions.

Day 30: Take a break and relax before the interview.

Monday, 14 January 2019

what is Forwardable module

The Forwardable module provides delegation of specified methods to a designated object, using the methods def_delegator and def_delegators.

For example, say you have a class RecordCollection which contains an array @records. You could provide the lookup method record_number(), which simply calls [] on the @records array, like this


class RecordCollection
  extend Forwardable
  def_delegator :@records, :[], :record_number
end

Sunday, 6 March 2016

SQL Query to second find highest salary of Employee

n= 0 for first record salary
n = 1 second highest salary 
n= 2 third highest salary 

SELECT DISTINCT(Salary) FROM Employees ORDER BY Salary DESC LIMIT n,1


Also some other queries 

select MAX(Salary) from Employee WHERE Salary NOT IN (select MAX(Salary) from Employee ); 


SELECT salary  FROM (SELECT DISTINCT(salary) FROM Employees ORDER BY salary DESC LIMIT 2) AS emp ORDER BY salary LIMIT 1;

Thursday, 3 March 2016

Difference between git merge and git rebase

I would suggest take an overview of this link, this would help you to understand actually how git rebase and merge works.