diff --git a/2016-10-31 Default scope in Rails b/2016-10-31 Default scope in Rails new file mode 100644 index 0000000..437a576 --- /dev/null +++ b/2016-10-31 Default scope in Rails @@ -0,0 +1,42 @@ +--- +title: Default scope in Rails +tip-number: 30 +tip-username: Gokul M +tip-username-profile: https://github.com/mgokul595 +tip-description: Using default scope in Rails Model + +--- + +```ruby default_scope ``` in Rails will apply the conditions on all queries on the Model. + +class Test < ActiveRecord::Base + default_scope { where(started: true) } +end + +```ruby +Test.all # => SELECT * FROM tests WHERE started = true +``` + +To using more complex queries inside the ```ruby default_scope ``` you can declare the class method as use it as below: + +```ruby +class Test < ActiveRecord::Base + def self.default_scope + # Query goes here + end +end + +``` + + +The default scope is applied on the ```ruby new ``` and ```ruby create ```. +If we initialize a new object it will set the value of the column to the default value that we specified in the ```ruby default_scope ```. + +For Example, + +```ruby +Test.new # Initializes a Test which contains started=true +``` + +So, be careful on using ```ruby default_scope``` +-- diff --git a/rails_tip/2016-10-31-Update without validation.md b/rails_tip/2016-10-31-Update without validation.md new file mode 100644 index 0000000..00bfda8 --- /dev/null +++ b/rails_tip/2016-10-31-Update without validation.md @@ -0,0 +1,36 @@ +--- +title: Disable model validation on update +tip-number: 30 +tip-username: Gokul M +tip-username-profile: https://github.com/mgokul595 +tip-description: Updating values in the Database without doing the model validation + +--- + + + + +Generally update_attributes method in rails will validate all fields eventhough it is not being updated. + +So, If we need to update the fields without doing such validations we can go with the below two methods: + +1. Updating the column one by one using update_attribute: + +```ruby +@object.update_attribute(first_name: 'Rails') +``` + +This will validate & update only the name field and skip validation for other fields. +Now, Just think what if you need to update more columns. It cause more queries to be executed instead of updating in single query. + +2. Updating the column values without any validation: + +```ruby +@object.assign_attributes(first_name: 'Ruby', last_name: 'Rails') +@object.save(validate: false) + +``` + +Using above method the validation of the columns can be skipped. + +--