Rails Cookbook - Advanced rails recipes/learnings and coding techniques All Versions
This draft deletes the entire topic.
Examples
-
Sometimes we want to use a
where
query on a a collection of records returned which is notActiveRecord::Relation
.Hence we get the above error asWhere
clause is know toActiveRecord
and not toArray
.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
asmap
will return anarray
which will not work withwhere
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 likemap
but they will beActiveRecord
and not anArray
. -
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 inusers
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
-
-
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 :).
Sign up or log in
Save edit as a guest
Join Stack Overflow
Using Google
Using Facebook
Using Email and Password
We recognize you from another Stack Exchange Network site!
Join and Save Draft