Getting started with Ruby on RailsRoutingActiveRecordViewsActiveRecord MigrationsRails Best PracticesNaming ConventionsActionCableActiveModelUser Authentication in RailsActiveRecord AssociationsActiveRecord ValidationsActiveRecord Query InterfaceActionMailerRails generate commandsConfigurationI18n - InternationalizationUsing GoogleMaps with RailsFile UploadsCachingActionControllerConfigurationSafe ConstantizeRails 5Authorization with CanCanMongoidGemsChange default timezoneAsset PipelineUpgrading RailsActiveRecord LockingDebuggingConfigure Angular with RailsRails loggerPrawn PDFRails APIDeploying a Rails app on HerokuActiveSupportForm HelpersActiveRecord TransactionsRSpec and Ruby on RailsDecorator patternElasticsearchReact with Rails using react-rails gemRails Cookbook - Advanced rails recipes/learnings and coding techniquesMultipurpose ActiveRecord columnsClass OrganizationShallow RoutingModel states: AASMRails 5 API AutheticationTesting Rails ApplicationsActive JobsRails frameworks over the yearsAdd Admin PanelNested form in Ruby on RailsFactory GirlImport whole CSV files from specific folderTools for Ruby on Rails code optimization and cleanupActiveJobActive Model SerializersRails Engine - Modular RailsSingle Table InheritanceActiveRecord TransactionsTurbolinksFriendly IDSecurely storing authentication keysAuthenticate Api using DeviseIntegrating React.js with Rails Using HyperloopChange a default Rails application enviornmentReserved WordsRails -EnginesAdding an Amazon RDS to your rails applicationPayment feature in railsRails on docker

Rails Cookbook - Advanced rails recipes/learnings and coding techniques

Other topics

Playing with Tables using rails console


View tables

ActiveRecord::Base.connection.tables

Delete any table.

    ActiveRecord::Base.connection.drop_table("users")
    ------------OR----------------------
    ActiveRecord::Migration.drop_table(:users)
    ------------OR---------------------
    ActiveRecord::Base.connection.execute("drop table users")

Remove index from existing column

 ActiveRecord::Migration.remove_index(:users, :name => 'index_users_on_country')

where country is a column name in the migration file with already added index in users table as shown below:-

 t.string :country,add_index: true

Remove foreign key constraint

ActiveRecord::Base.connection.remove_foreign_key('food_items', 'menus')

where menus has_many food_items and their respective migrations too.

Add column

ActiveRecord::Migration.remove_column :table_name, :column_name

for example:-

 ActiveRecord::Migration.add_column :profiles, :profile_likes, :integer, :default => 0

Rails methods - returning boolean values

Any method in Rails model can return boolean value.

simple method-

  ##this method return ActiveRecord::Relation
  def check_if_user_profile_is_complete
    User.includes( :profile_pictures,:address,:contact_detail).where("user.id = ?",self)
  end

Again simple method returning boolean value-

  ##this method return Boolean(NOTE THE !! signs before result)
  def check_if_user_profile_is_complete
    !!User.includes( :profile_pictures,:address,:contact_detail).where("user.id = ?",self)
  end

So,the same method will now return boolean instead of anything else :).

Handling the error - undefined method `where' for #<Array:0x000000071923f8>

Sometimes we want to use a where query on a a collection of records returned which is not ActiveRecord::Relation.Hence we get the above error as Where clause is know to ActiveRecord and not to Array.

There is a precise solution for this by using Joins.

EXAMPLE:-

Suppose i need to find all user profiles(UserProfile) which are active which is not a user(User) with an id=10.

UserProfiles.includes(:user=>:profile_pictures]).where(:active=>true).map(&:user).where.not(:id=>10)

So above query will fail after map as map will return an array which will not work with where clause.

But using joins,will make it work,

UserProfiles.includes(:user=>:profile_pictures]).where(:active=>true).joins(:user).where.not(:id=>10)

As joins will output similar records like map but they will be ActiveRecord and not an Array.

Contributors

Topic Id: 7259

Example Ids: 24192,24207,24263

This site is not affiliated with any of the contributors.