rails-snippets-devel#
Gemfile#
Rakefile#
namespace :db do
task :recreate => [ :drop, :create, :migrate ] do
if ENV[ 'RAILS_ENV' ] !~ /test|cucumber/
Rake::Task[ 'db:seed' ].invoke
end
end
end
Example of DB load (Hartl books)#
bundle exec rake db:populate
namespace :db do
desc "Fill database with sample data"
task populate: :environment do
admin = User.create!(name: "Example User",
email: "[email protected]",
password: "foobar",
password_confirmation: "foobar",
admin: true)
99.times do |n|
name = Faker::Name.name
email = "example-#{n+1}@railstutorial.org"
password = "password"
User.create!(name: name,
email: email,
password: password,
password_confirmation: password)
end
users = User.all()
50.times do
content = Faker::Lorem.sentence(5)
users.each { |user| user.microposts.create!(content: content) }
end
end
end
bundle exec rake db:populate --trace
This is what brought the question about
Use
> users = User.all.limit(6)
or just
> users = User.limit(6)
[The 'all' method doesn't take parameters.] (http://apidock.com/rails/ActiveRecord/Scoping/Named/ClassMethods/all)
http requests#
You can add this current_url method in the ApplicationController to return the current URL and allow merging in other parameters#
# https://x.com/y/1?page=1
# + current_url( :page => 3 )
# = https://x.com/y/1?page=3
def current_url(overwrite={})
url_for :only_path => false, :params => params.merge(overwrite)
end
Example Usage
>current_url --> http://...
>current_url(:page=>4) --> http://...&page=4
forms processing#
def create
@page = Page.new(params[:page])
@page.save! # notice the "!"
flash[:notice] = "Page saved"
redirect_to :action => 'index'
rescue ActiveRecord::RecordInvalid
render :action => 'new'
end
Just ways of coding#
result += (@days_overdrawn -7) * 0.85 if @days_overdrawn > 7
# this loops on itself (aka +=)
def calculate_outstanding
@orders.inject(0.0) { |result, order| result + order.amount}
end
def calculate_outstanding(initial_value)
@orders.inject(initial_value) { |result, order| result + order.amount}
end
# put the method's body into the body of its callers
def get_rating
more_than_five_late_deliveries ? 2 : 1
end
def more_than_five_late_entries
@number_of_late_deliveries > 5
end