Skip to content

Instantly share code, notes, and snippets.

@nadeem-khan
Last active November 6, 2017 12:48
Show Gist options
  • Save nadeem-khan/9d1ba457559df168e3df to your computer and use it in GitHub Desktop.
Save nadeem-khan/9d1ba457559df168e3df to your computer and use it in GitHub Desktop.
Rails Commands

New Rails Project:

 rails new blog

Run Rails Console:

RAILS_ENV=production rails c  (restart console too whenever you make a change in the model)

View All Routes:

rake routes

Find Count of All Records:

RecurringTask.all.count  (count all records in recurring task model)

Update a Column Value:

Issue.find(25).update_attributes(closed_on: '2014-07-23')

View All Columns:

Issue.inspect (will show all columns)

Check for a Method for the First Object:

Issue.first.some_method

Check for a Method for the Last Object:

Issue.last.some_method

Generate a Migration:

rails generate migration AddNewColumnsToSearchItemImages

Add Columns to Existing Table by Creating a New Migration:

class AddColumnsToUsers < ActiveRecord::Migration
  def change
    add_column :users, :provider, :string
    add_column :users, :uid, :string
  end
end

Revert Some Old Migration:

 RAILS_ENV=production rake redmine:plugins:migrate NAME=redmine_issue_templates VERSION=20140707202847

Run Migration for a Specific Plugin Only:

RAILS_ENV=production rake redmine:plugins:migrate NAME=redmine_issue_templates

Access join table of Products and Taxons models in rails console

 Spree::Product.find(17).taxons

Remove Cache Folder

rm -Rf tmp/cache     

Search by Convention (Column Names)

Spree::Taxon.find_by_permalink('bath-and-body')

Run a rake task

rake luxuryperfume:generate_categories

Get an array of all ids of a model

Spree::Product.all.map(&:id)    

Select Related Objects in a Query?

   p = Person.where(job: 1).includes(:jobs)
   job = p.job.job_name
   
   people = Person.where(status: 'active').includes(:jobs)
   people.each {|p| puts p.job.job_name}

Find all records where two conditions are true

Person.where(:state => "Wisconsin", :single => true)
 OR
Person.find_all_by_state_and_single("Wisconsin", true)

Multiple Conditions

Request.pending.where('(approver1_id= ? AND state_id= ?) OR (approver2_id= ? AND state_id= ?) OR (approver3_id= ? AND state_id= ?)', current_user.id, 1, current_user.id, 2, current_user.id, 3)
OR
state_id = [1, 2, 3]  
Request.pending.where(:state_id => state_id AND :approved_id => current_user.id)
OR
Request.pending.where('state_id IN [1,2,3]')

Check if variable present and not empty

def show
@city = @user.city.present? #The present? method tests for not-nil plus has content. Empty strings, strings consisting of spaces or tabs, are considered not present.
end

scope through associations : joins and merge

scope :current, where('transactions.start_date IS NOT NULL AND transactions.end_date IS NULL').order("by whatever").limit(1)

Using Merge

bob = User.where(email: "bob@test.com").where(active: true)
# => SELECT "users".* FROM "users" WHERE "users"."email" = 'bob@test.com' AND "users"."active" = 't'


 details = User.select(:id, :email, :first_name).order(id: :desc)
# => SELECT "users"."id", "users"."email", "users"."first_name" FROM "users" ORDER BY "users"."id" DESC


bob.merge(details).first # Merges in the conditions from other, if other is an ActiveRecord::Relation. Returns an array representing the intersection of the resulting records with other, if other is an array.
# => SELECT "users"."id", "users"."email", "users"."first_name" FROM "users"
#    WHERE "users"."email" = 'bob@test.com' AND "users"."active" = 't'
#    ORDER BY "users"."id" DESC LIMIT 1

Check how rails is generating params

go to log/development.log then press shift+g and then do ctrl+r and find the expression

how to use link_to

links << link_to('more', mens_cologne_path(search: {brand_any: [product.property("Brand")]})) #search onwards will be added in the url

Find duplicate lines in a file

# produce an array where each item is a separate line from the file
lines = File.open("changelog").readlines
# produce an array where each item is a separate line from the file
lines = File.open("changelog").readlines

  lines.select do |line|
   # check if current line appear more than once in the array
  lines.count(line) > 1
 end

Join with interim tables

   def product_category_ids(product)
    @@taxonomy_category ||= Spree::Taxonomy.find_by_name('Categories')

    categories = product.taxons.where(taxonomy_id: @@taxonomy_category.id)
    categories = categories.select{|c| c.leaf?}
    categories.map(&:id)    
   end

  @@men_products_ids ||= Spree::Taxon.find_by_name("Men's Cologne").product_ids

men_products = Spree::Product.joins(:taxons).
  where("#{Spree::Product.table_name}.id in (?) AND #{Spree::Taxon.table_name}.id in (?)", 
  @@men_products_ids, product_category_ids(product)).group("#{Spree::Product.table_name}.id").order('rand()')

links = []
men_count = 0
if men_products.any?
  men_products.limit(6).each do |men_product|
    links << link_to(men_product.name)
  end
  men_products.each do |men_product_count|
    men_count += 1 
  end
end

if men_count > 6
  links << link_to('more', mens_cologne_path(search: {brand_any: [product.property("Brand")]}))
end
links.join(', ').html_safe
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment