Anki Rails

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

you have a category which calls it's posts and that post's comments AND TAGS and those comments' guests... how to optimise this nesting using ActiveRecord includes

"Category.includes(:posts => [{:comments => :guest}, :tags])"

how to order Clients by orders_count ascending and created_at descending

"Client.order(""orders_count ASC, created_at DESC"")"

ActiveRecord - how to get only the viewable_by and locked columns of Client model and nothing else

"Client.select(""viewable_by, locked"") # pass select a string with comma separated column names"

how to get this to work (Date.today - 1.day.ago).to_f instead of returning a type mismatch

(Date.today - 1.day.ago.to_date).to_f

how to make a rails app from template

-m option r new testgen -m tdd_template.rb

rails - if you place an image into /public from what url is it accessible from

/image-name.png

you have defined a custom time format :email how to use it

Time.now.to_s(:email)

why might a route named correctly otherwise fail e.g. unsubscribe_path

because routing requires mandatory params (e.g unsubscribe_path(:id=>2))

"whenever you see an ""app"" method or variable in rails source code, this usually refers to"

a rack application

how to make this work u.habits.offset(2)

add a limit to the chain u.habits.limit(365*150).offset(2)

how to you make a digest password even more secure (second stage)

add a salt - i.e. a small amount of random data so that the digest cannot be used as easily

rails - how to performance test in dev mode

add ruby-prof gem when newrelic_rpm is already there turn on profiling at /newrelic

fix - ActionView::Template::Error (Could not find a JavaScript runtime)

add therubyracer to your gems

rails - apply routing constraints to a block of resourceful routes (e.g. that id is a number) resources :photos resources :accounts

constraints(:id => /[0-9]+/) do resources :photos resources :accounts end

session (in rails) is a kind of ..

cookie

rails - why could this blow up RAM? User.has_purchased(true).each do |customer| customer.grant_role(:customer) end

could load GBs of data in memory if there are many users prefer .find_each or find_in_batches

rails - count all columns which have marketing_mode column without any value

count(:conditions => {:marketing_mode => nil})

every instance method you defined in a class which inherits ActionMailer::Base will....

create Mail object looking for a view by that name

if you have common functionality in the middle of many controller methods how do you dry?

create a private controller method and put this code here... or better yet delegate to a model/include a module that does this work

"rails - what does this do caches_action :index, :layout => :false"

caches stuff inside view but not layout... letting you add things you don't want cacheable such as user logged in / off to the layout

how to view the sql which a named scope turns into

call .to_sql on the scope e.g. User.published.to_sql

"rails - what does this do <%= render @products, :spacer_template => ""product_ruler"" %>"

gets a second partial rendered between instances of the main partial

"what does this do: Client.select(""DISTINCT(name)"")"

gets only a single record per unique value in the name field

how to overcome rails mistakes in pluralization

give custom instructions for a rule in initializers/inflection

how to customize (statically) the error pages in rails

go to public/ folder and you see 404.html files etc.

ignore duplicate associated objects by accessors and query methods

habtm :tags :uniq => true

rails - convention for what to call observer files?

modelname_observer e.g. for a Result model result_observer (no plurals)

rails - missing constant (undefined) errors in javascript can often be fixed by

modifying the load order in the application.js manifest file (e.g. loading handlebars before the backbone view files which use handlebars)

how does validates uniqueness of fail if an attribute is left blank

it doesn't fail the first time.. rather it fails the second time as you are saving nil twice (un-unique)

rails - gotcha with memoize

it has to come after method is declared

If a resourceful route (applicants) has a member method (mail) what is its named route?

mail_applicant_path(@applicant) # the member name comes before the resource name

solution for: comparison of Date with ActiveSupport::TimeWithZone failed

make sure both attributes being compared are same type - e.g. datetime or date. Change in the database or use .to_date type conversions in the comparision methods.

rails - you have mailers/marketing_mailer do views go in: mailers/marketing_mailer/ OR marketing_mailer/

marketing_mailer/

what's wrong here resources :habits do member :succesfully_completed_today member :unsuccesfully_completed_today end

member is a block (get etc. always prefixes rails routes names) resources :habits do member do get :unsuccesfully_completed_today end end

what does string.squish do in rails

removes whitespace on left and right and removes double spacing within the string

how to transform text into HTML in rails

simple_format double newlines => p one newline => br

"when you are doing translation in rails (with a yml) file what yml entry will this have t(""sell_your_notes"")"

sell_your_notes i.e. it must be exactly the same

what does :dependent => :nullify do in a has many object

sets all associated objects foreign keys to null without calling their save callbacks

rails - what does this mean in the logs: SAVEPOINT active_record_1

start of a transaction

What does enforcing the use of proper HTTP request methods ensure?

that simple attacks such as embedding a url in an <img> or <link> tag are thwarted

how long does a rails session last

until the user closes his browser # flash lasts one request # cookies as long as you specify

rails - when adding a new database column which defaults to false what must you also do

update all existing (which will now be null) to false

you have a Category which calls its Posts and each post's comments and those comment's guest... how to optimise this nesting using includes

use a hash for each level of nesting Category.includes(:posts => {:comments => :guest})

what should you do if it is imperative that you only create an object with certain attributes only once

use find_or_create_by_attr()

how to convert a number into a month name in rails

Date::MONTHNAMES[Time.now.month]

thor - how to copy a file

"copy_file ""source"""

rails - how to get a migration to run sql directly

"def self.up execute ""alter table settings add name varchar"" end"

How to have it so that the return value of @user in a view or debugger gives you the return value of that user's fullname method

override User#to_s def to_s fullname end

someone visits a url like this: articles?hidden=true how to access this hidden parameter in the controller?

params[:hidden]

step 1 in outside in development

start with a scenario -- have a clean understanding of expected outcomes

"what does this do: <%= form_for(@post, :as => :client) do |f| %> ... <% end %>"

the post parameters now appear in params as :client

rails -- how to get a number to express itself as x days

x.days (crazy huh)

rails - can you do button_to :remote => true

yes

rails - can you use named paths with current_page? current_page?(applicants_path)

yes

rails - do before_filters work with caches_action?

yes

rails - does update_attributes run validations

yes # compare to update_attribute which doesn't run validations

"can you delegate multiple fields in Rails with this delegate :discipline, :institution, :to => :notes_pack"

yes - as many as you like

are gem names case sensitive

yes - pay attention

rails - why do assets have an md5 fingerprint

so files are cached by browsers (and invalidated upon change) and ISPs # known as cache busting

how to just get a url (without any anchor text) using url helpera in rails

"# omit the first argument, ""text string"", when calling link_to <%= link_to blog_path %>"

how to solve Errno::EAFNOSUPPORT (Address family not supported by protocol - socket(2)): when sendmail with rails/heroku

"add a default url option to production config.action_mailer.default_url_options = {:host => ""www.mysite.co.uk""}"

"what is shorthand for Article.order(""published_at asc"")"

"Article.order(""published_at"")"

how to update all billing objects with three given attributes?

"Billing.update_all( ""category = 'authorized', approved = 1, author = 'David'"" ) # or with hash notatation Message.update_all({:read => true}, {:id => user.messages})"

"Rewrite this ActiveRecord query to work: Blog.all(:conditions => [""thumb != ?"", nil])"

"Blog.all(:conditions => ""thumb is not null"")"

what should the index on a has_and_belongs_to_many table look like and is it necessary

"CRAZY NECESSARY -- should have both id columns indexed for speed add_index :developers_projects, [:developer_id, :project_id]"

how to get the total count of all Grinds who have their county field set to 'mayo'

"Grind.count(:conditions => ""county = 'mayo'"")"

rails - Before pulling out a debugger what file should you inspect?

"Looking at the rails log carefully - which controller was rendering, what params were passed, what sql was run"

ActiveRecord#update_all is used to

"Mass update many objects # Conditions from the current relation also works Book.where('title LIKE ?', '%Rails%').update_all(:author => 'David')"

Compute the sum of all values for a Model's column

"Person.sum(""age"")"

"how to get the attributes for an active record object but for id, updated_at and available_on"

"Product.first.attributes.except(""available_on"", ""count_on_hand"", ""created_at"", ""id"")"

how to set something to the cache (or read it if already exists in the cache)

"Rails.cache.fetch(""categories"") {Category.all} # looks for categories entry in the cache, setting it to Category.all otherwise"

how to make AR where hash notation use and SQL IN operator

"Student.where(:grade => [1,2,3,4])"

rails - programmatically stop callbacks (skip the :generate_zip_file save callback on Subject)

"Subject.skip_callback(:save, :after, :generate_zip_file) # note you have to set_callback with the same args to re-enable it"

Did these cards help you to learn Rails?

"Then please send a small donation (~$9) to their creator, Jack Kinsella. He spent many hours preparing these for your benefit, clarifying technical details, removing redundant cards and publishing his findings. http://www.oxbridgenotes.co.uk/other/web_development_flashcards#donate"

"Rails - [1,2,3,4].in_groups_of(2)"

"[[1,2], [3,4]]"

compute the maximum for a Model's column

Person.maximum('age')

What is the principal time you should use extra logic in a controller and not a model

To render different things or redirect

"which is correct: Habit.where(""name ='N'"") Habit.where('name =""N""')"

"only Habit.where(""name ='N'"")"

"capybara - check for a button with id ""create_products"""

"page.has_button? ""create_products"" # note the lack of a # in front of the create_products id"

rails/capybara - test for an image's presence

"page.has_selector? ""img[src$='#{image_name}']"" # notice the src$ selector to check for the end of the attribute (avoids prefixes like small_image_name.png which some Rails gems add)"

how to find multiple items with find_by_id

"pass it an array of values User.find_by_id([1, 12, 55])"

how to get the total count of all Users whose paid attribute is not nil in the database

User.count(:paid)

"What db column likely exists given this HTML code on a Rails app? <input id=""user_first_name"" name=""user[first_name]"" size=""16"" type=""text""/>"

User.first_name # importance: Forms can betray your data structures and possible security holes

You have a scope on the User model (.with_orders) and a scope on the Order model (.complete) -- how to combine the two to find users with complete orders

User.with_orders & Order.complete

rails call a method right after initialization of ActiveRecord instance

after_initialize :method

ActiveRecord callback on records saved or destroyed within a transaction immediately after the transaction or savepoint is rolled back

after_rollback

:counter_cache requires what column (e..g. Comment model)

comments_count

how to add something to rails' load path in rails 3

config.autoload_paths += %W( #{Rails.root}/app/observers )

how to change the default template_engine to haml

config.generators do |g| g.template_engine :haml # assumes you've got the haml gem installed

how to access your normal routes from within an engine

main_app.my_named_url # prepend main_app # be careful not to do this kind of thing in gemified engines as it destroys the abstraction

how to use a helper from the primary app in an engine

main_app.root_path main_app.products_path

rails - how to duplicate a record

new_record = old_record.clone # unsaved record # does not copy associations

you have a resource (products) namespaced under sellers what is the new seller url helper

new_sellers_product_url

"if an AR finder finds nothing what will it return find_by_name(""First-Steps"")"

nil

a non existent param (e.g. param[:unicorn]) has what value?

nil

"can you name an ActiveRecord column ""type""?"

no - type is reserved for polymorphic models

"rails - should you ever have a ""home_path"""

no -easier to just use root_path

will this work to push something into a @samples hash? @samples << []

no << syntax doesn't work with hashes

"[1,2,3,4,5,6,7].split(4)"

"[[1,2,3,],[5,6,7]] splits around the delimiters which isn't included in the return value # Array#split is only available in Rails. Ruby does, however, have a String#split"

What gotcha should you be aware with numerical values in params (which are to be used in mathematical operations)

params are always strings => usually you must convert them using to_i before doing mathematics

how to give defaults in action mailer

"a default class macro which accepts a hash e.g. default :to => ""[email protected]"" # can be overridden on a method by method basis"

rails - join table what kind of index is necessary

"a double index add_index :keyword_locales, [:keyword_id, :locale_id]"

"what does this do LineItem.sum(:quantity, :group => :variant_id, :limit => 5)"

"a hash, with the variant id as the keys (group), and the quantity as values, with no more than 5 entries"

how to get the 2nd and 3rd items in a ruby array

"a[1, 2]"

rails - get an alternative image displayed on mouseover of an image_tag

"image_tag(""mouse.png"", :mouseover => ""/images/mouse_over.png"")"

you've created an observer in Rails. how to get it run?

"in application.rb add: config.active_record.observers = :result_observer, :garbage_collector (alternatively just activate them per controller by adding cache_sweeper :garbage_collector)"

shortest way to render a partial (shared/taxonomies)

"omit the :partial <%= render ""shared/taxonomies"" %>"

rails - how to get into database to do sql

r dbconsole

rails - how to have multiple root urls

"one per namespace namespace(:admin) do root :to => ""dashboard#show"" namespace(:my) do root :to => ""dashboard#show"""

rails - how to get etag to be based on product and current_user

"pass an array fresh_when etag: [@product, current_user]"

how to mass create new objects in rails

"pass an array of hashes of attributes to create User.create([{ :first_name => 'Jamie' }, { :first_name => 'Jeremy' }])"

how to add multiple callbacks on associations

"pass in an array of symbols of the method name has_many :comments, :after_add => [:do_this, :and_this]"

in rails views how to conditionally pluralize a word

"pluralize(6, ""dog"") => ""dogs"" pluralize(1, ""dog"") => ""dog"""

rails - erb is an example of a ....

"pre-processor not just limited to html.erb txt.erb allows you to add <%= %> to txt files, for example"

how to load something before rails 3 initializes

"put in before require ""rails/all"" in application.rb"

best practice for rails helpers

turn them off at generator level as most won't be used (and take up memory)

rails 3.2 Array.prepend & Array.append are aliases for

unshift & <<

can you add a line of code to a gem's files locally (opened using bundle open) and expect it to work on server restart in Rails

yes

Rails - does update_attributes save the record?

yes it does

Why should you use :select in ActiveRecord queries?

"since often you rarely will need all the data ActiveRecord usually provides # and so you will reduce database traffic, memory bloat and so improve performance"

what happens to counter cache when an object is created or destroyed

it is incremented and decremented

"what named url helper does this give namespace :admin do match ""uploads"" => ""uploads_overview#index"", :as => :uploads_overview end"

admin_uploads_overview #NAMESPACE is prepended to nested routes

why can't you access after_filter variables in the view

after_filter is executed after the call to render

"what does this code do? Class Order delegate :email, :to => :checkout end"

allows you to call order.email despite the Order table having no email column (instead it uses the email column on the checkout table)

rails - what does this structure do extend ActiveSupport::Concern included do def self.page end end

allows you to specify a block of methods to be included whenever the module containing the code show above is included

rails 3.1 what is the j helper method

an alias for JavaScriptHelper#escape_javascript()

what does @object.save! return if validations fails

an exception - ActiveRecord::RecordInvalid: Validation failed

any field used in an order_by clause should have what in the database layer?

an index

any field using a validates_uniqueness should have what in the database layer

an index

rails - what does dependent :delete do (as opposed to :destroy)

deletes the associated object... but without calling it's destroy method (thereby avoiding it's callbacks)... possible problem is that this might leave orphaned records behind as its dependent items won't get destroyed

"limits of hash notation for where statements such as Student.where(:first_name => ""Harvey"", :status => 1)"

conditions always generated on equality with the SQL AND operator

How to activate caching in rails at the env level

config.action_controller.perform_caching = true # note that this requires you to write to file system (=> it won't work on read only servers like heroku)

how to get rails to deliver emails in dev mode

config.action_mailer.perform_deliveries = true config.action_mailer.delivery_method :smtp (or :sendmail) config.action_mailer.smtp_settings = { # hash of settings }

How to reload your rails app on every request

config.cache_classes = true (in an environment file) # slows it down but good for debugging

how to switch off stylesheets in rails generators

config.generators do |g| g.stylesheets false end

how to get rails to hide all the sql in its logs

config.log_level = :info

rails - if you want to add a method to a class of a gem from within your app where do you do it?

config/initializers why? because they are loaded AFTER all plugins and gems so you won't get constant missing errors when you try to monkey patch

if lots of items share db data (state) what is a good name for this shared content

content_base (which would be a polymorphic model bt :profile_models etc.)

how to get create to raise an exception if validations fail

create!

"a User model has_many :sent_messages, :class_name => ""Message"", :foreign_key => ""sender_id"" how to define a method in the User model which succinctly creates a message which will auto populate the sender_id"

def send_message(message_attrs) sent_messages.create! message_attrs end

when you have a nested resource how do you access the id of the outer resource

params[:outer_resource_id] # think about it - the outer resource is in the url e.g. notes_pack/3/subjects

avoid any model names that end in

s ... since rails's magic expects model names in the singular and auto-generates methods and so on on this basis

which is preferred on greenfield projects: sass or scss

sass - its much more concise and has less syntax

Rails - what happens if you use update_attributes and the saving fails (e.g. invalid object)

save fails and false is returned... nothing is raised however

how to save skiping validations

save(:validate => false)

rails - you want a controller namespaced under FacebookApp but you want the route to be trackings_path instead of a namespaced facebook_app_trackings_path

scope :module => :facebook_app do resources :trackings end

"how to get past this issue when editing multiple items in one form object[] naming but object param and @object var don't exist or don't respond to to_param: nil e.g. @habits.each do |habit| semantic_fields_for ""habit[]"" ...."

set @habit to habit <% @habit = habit%>

rails - what is <%== %>

shorthand for <%= raw( )%>

rails - why is caches_page so fast?

since Rails process never even gets hit... it just goes straight to public/my-cached-page on hardrive nginx/apache just fetches it

rails - why should you not let users uploads file to Rails public directory

since files such as virus.cgi will be executed by apache when someone requests it

what to name the foreign key in a polymorphic model (e.g. comment)

something a little more abstract / generic which captures what every one of models associated with that comment have in common e.g. instead of photo_id => commentable_id

what's a very bad name for an association model

something with the same name as an instance method of ActiveRecord::Base # the association method will override the instance method and break things

what error will this give? (rails where db attr display_name) def display_name display_name || full_name end

stack level too deep - recursion keeps calling itself

Request-URI Too Large with rails

switch to thin server

within a Rails 3 rake task how do you call a custom environment

task :name => :environment

In a rails app where are performance tests

test/performance folder

if a db column in Rails will have more than 255 characters it should be specified not as a string but as a

text column

rails - a sweeper's class name is XSweeper - what should x refer to

the controller whose cache you are sweeping

to what url does this form post it's attribute to <%= form_tag do %> Form contents <% end %>

the current page is its action by default

what happens if any of the before_add or before_remove callbacks cause an exception

the object does not get added to the collection / removed

what does rails reverse_merge do

the opposite of merge - keys and values from the receiver hash take precedence over the argument hash

rails - every cookie sent to a client's browser contains what

the session_id

what is the use case for time_ago_in_words (vs distance_of_time_in_words)

time_ago_in_words compares with the current time so only takes one parameter

rails - when creating a custom migration for a new model what should you not forget

timestamps

what to be aware of with time comparisons in Rails

timezones (e.g. 30.minutes.from_now might be in a different time zone to Time.now)

db - what to always remember with boolean columns

to consider making them false by default since otherwise you might have confusion between null and false in something like Rails finder methods.

when doing javascript integration testing in a rails app what must you remember?

to use _path instead of _url to refer to urls in your tests otherwise redirect to example.com

"rails - you have a route: match ""unsubscribe/seller"" what is the named path"

unsubscribe_seller_path

when doing css design in rails you should

use livereload to automatically update in browser without refreshing

how to improve this? def edit @post = Post.find(params[:id]) if @post.user != current_user flash[:warning] = 'Access denied'

use scoped access @post = current_user.posts.find(params[:id])

when to use update_attribute over update_attributes?

use update_attribute to update a single attribute. You might chose it since it bypasses validations so its nice and fast and less brittle.

how to get the comment ids of an association model (a user's comment_ids)

user.comment_ids

how to add an object to a has_many collection (comments in this example) without saving it automatically

user.comments.build # call user.save to save the new comments

"when you want someone to ""accept"" terms what validation is used"

validates_acceptance_of

what is your first line of defense in a rails app

validations - validate data heavily (never trust users or other systems)

rails - how is the relevant session data (stored on your server) identified to the user

via the session_id in the cookie

rails 3 what has this turned to Email.deliver_welcome

Email.welcome.deliver

rails - how to expire a page in a sweeper

"expire_page(:controller => 'products', :action => 'index')"

rails - an existent but empty param has what value

""""""

rails - what will check_box_tag default to in the params if selected

"""1"""

"rails - capitalize every word in a string ""oh my god"" -> ""Oh My God"""

"""oh my god"".titlecase (ActiveSupport)"

you have fields_for another model in a form (notes_file fields in subject form) - what will the params structure look like

"""subject""=>{""notes_file""=>"

rails - how to just get one column of an association returned by default

"# adding a select has_many :uids, :class_name => ""Award"", :select => ""winner_id"""

rails - how to subscribe to the notification products.search and do something

"# in an initializer ActiveSupport::Notifications.subscribe ""products.search"" do |name, start, finish, id, payload| # do something end"

how to link to destroying a model

"# link_to the object itself (testimonial is the || of @testimonials) and call method with :delete <%= button_to ""Delete"", testimonial, :method => :delete %> # Rails 3 needs buttons"

rails - how to set an inline attachment in mailer

"# mailer code # e.g. within def send_introduction attachments.inline['jack_kinsella_120.jpg'] = File.read(Rails.root + ""public/images/jack_kinsella_120.jpg"")"

Why should you sometimes save without validations?

"1. because validations take up processing power and often you don't need that overhead (e.g. updating the view count of a blog post) 2. at some point (e.g. user just bought 1000 credits), you don't want their transaction invalidated because their email format was wrong"

what does this return number_with_delimiter(123456)

"123,456"

"Rails - find all students with grades 9,11 or 12 using a conditions hash"

":conditions => { :grade => [9,11,12] }"

ActiveRecord models - if one attribute just isn't saving should you check?

"If you have the right data types in the database # Once I had a date field in the DB, but my code was trying to put in strings - it passed validations but never got saved to db."

what happens whenTopicFile.create is called with data that won't validate

"It will still return an object, though it silently won't save"

"what's wrong here: #.js view $('#foo-list').css('background', 'yellow').html(""<%= render('foo')) %>"");"

"you need to escape_javascript (alias j) since js will be unhappy with the contents of the render here $('#foo-list').css('background', 'yellow').html(""<%= j(render('foo')) %>"");"

RAILS why might you get this error in a named scope ActiveRecord::ReadOnlyRecordError

"you used a join in the named scope fix with: has_many :habits, :readonly => false"

rails - how to get an inline attachment into email

# View code <%= image_tag attachments['jack_kinsella.jpg'].url -%>

where to put custom exceptions in a Rails app

# lib/exceptions.rb module Exceptions class TooLazyToWork < StandardError; end class NotTheBoss < StandardError; end end

if a magazine has many comments and you want to route things like magazines/1/comments. how?

# nested resources resources :magazines do resources :comments end

has_and_belongs_to_many :object/:objects? should the object be singular or plural?

# plural... like natural language has_and_belongs_to_many :cases

remove a gem you just released (facebook_app)

# requires you have gemcutter gem installed - gem install gemcutter gem yank facebook_app

rails sass - set #navigation ul and later #navigation li

# use indentation #navigation ul :list-style none :padding-left 0px li :display inline :margin-right 20px

your create method of a controller reads like this - what to do? def create @product = Product.new(params[:product]) @detail = Detail.new(params[:detail]) Product.transaction do @product.save! @detail.product = @product @detail.save end end

# use nested attributes since this will mean that the product model can handle the creation of the detail model. Now the create method looks the same as if there was no associated details creation logic :-) class Product < ActiveRecord::Base has_one :detail accepts_nested_attributes_for :detail end def create @product = Product.new(params[:product]) @product.save end

what needs to be in your application layout for http DELETE/POST methods to work

#NAME?

how to specify that a rails controller skip the authenticity check?

#in the particular controller skip_before_filter :verify_authenticity_token

"rails - if you are using caching in an action on the pages controller and have a sweeper how to ""register"" it"

#within the pages controller cache_sweeper :product_sweeper

Obvious refactor here? def create @post = Post.new(params[:post]) @post.user_id = current_user.id @post.save end

#you don't need to assign the user_id - just scope the creation and call create with the params for the model you want to create def create @post = current_user.posts.create(params[:post]) end

sass - declare a variable

$primary_color: #4cc

"count, sum, average, minimum and maximum are all really shortcuts to"

.... calculate thus you can feed them all the calculate options

"sql, rails - order by count of attendances"

.order('count(attendances.id) desc')

in which of the below will counter_cache values will be used .length .size

.size only

"rails 3.1 - url for an image ""galway_hooker.jpg"""

/assets/galway_hooker.jpg

"how to get rails to convert 1 to ""1st"""

1.ordinalize

Get the time 3 years in the past?

3.years.ago

Get a time 3 years in the future

3.years.from_now

rails 3.1 5 weeks ago

5.weeks_ago (as well as .weeks.ago as in previous versions)

convert the integer 6 to a float

6.to_f

rails - what will be the first line inside your sweeper class

"observe Modelx, Modely"

"how to get rails to give you this for @comment with id 123 <div id=""comment_123"" class=""comment""> ... </div>"

<% div_for(@comment) do %> ... <% end %>

how to use content_for to store something in :head

<%= content_for :head do %> <title>My site </title> <% end %>

rails associations -- diff between << and setting using = from db point of view

<< instantly fires sql update

how to call something previously stored via content_for :head {#content}

= content_for :head # same as storing except no block # alternative = yield :head

what error is thrown if no route matches

ActionController::RoutingError

How to clear emails (useful in tests)

ActionMailer::Base.deliveries.clear

"cure for ""hostname was not match with the server certificate exception notifier"" when a rails app tries to send email (specifically from a gmail account)"

ActionMailer::Base.smtp_settings = {:enable_starttls_auto => false} in an initializer

how to override an existing default scope in an ActiveRecord model

Article.unscoped {find :all } => #select * from articles #no scope used

encode a string in Rails

Base64.encode64s(str)

What is in the manifest.yml file

A list with all your assets and their respective fingerprints. This is used by the Rails helper methods and avoids handing the mapping requests back to Sprockets.

rails 3.1 - rewrite this Client.select('DISTINCT name')

Client.select(:name).uniq

give an example of a polymorphic variation of a User model

Create an extra model which inherits from User class DbUser < User end # now put custom validations and methods here

You should never use visual only security measures (e.g. removing the vote button from screen following a vote). What to do instead?

Enforce security at the server level so that it can't be hacked by spoofing a request. (In this case you might use cookie-tracking or login functionality to ensure one vote per user.)

Heroku/deployment If text appears garbled on your machine after copying your database from remote what should you do?

Ensure encoding is set correctly (usually utf8) in database.yml

how to get the total count of all Grinds in the database

Grind.count

when should you use attr_protected?

If you don't hackers can insert their own form ï¬Åelds to form pages and a typical application using mass assignment will gladly set values if a column exists that matches that field.

"If you call a system command within a rails program / rake task, where the working directoy be?"

In the Rails root folder

How to configure your rack middleware stack

In the enviroment files modify config.middleware config.middleware.use Rack::BounceFavicon

"what's wrong with this in a controller: Articles.find(:all, :conditions => ...)"

It's not a named scope. You should be packaging up finders into named scopes for reusability.

If a form in rails isn't working what is a good place to start debugging

Make sure the form is posting the parameters to the correct action in your app (refer to the logs)

"what's wrong with this: class Post < ActiveRecord::Base has_many :comments def find_valid_comments comments.find(:all, :conditions => {:is_spam => false}, :limit => 10) end end"

Models should not know too much about their association's finder logic - it destroys coupling. Thus we should move the valid comments finder to the comment model. # Comment Model scope :only_valid .. scope :limit ... # Posts controller @comments = @post.comments.only_valid.limit(10)

"rails - <textarea id=""message_body"" name=""message_body"" is id or name used as the param name in rails"

NAME

What should you optimize for when you want to improve the running speed of unit tests in typical web apps?

Not touching the db (e.g. ideally you can run the tests in under 10 seconds)

give an example of using [].sum WITH a block in rails

Orders.all.sum {|o| o.total}

button_on by default send its request as

POST

compute the average for a Model's column

Person.average('age')

What HTTP method is used by: <%= form_tag do %> Form contents <% end %>

Post

how to get all associated objects ids (e.g. product has_many line_items)

Product#line_item_ids

get the last two Products

Product.last(2)

make this work: Product.all.limit(2)

Product.limit(2).all # problem is that .all returned an array which does not have the limit method

how to clear a Rails cache?

Rails.cache.clear

"Create a new ""commission"" ActiveRecord model in vim"

Rmodel commission!

How to create a scope which gets all of the Seller records with Subjects (where Seller has_many Subjects through Packs)

Seller.joins(:packs => :subjects)

ActiveRecord - get every instance of a model except the current one (self)

Show.where(:act_id => act_ids).to_a - [self]

what to test in named scopes?

That they correctly find the objects you expect from the universe of objects you created

To prevent XSS attacks what should you do in views?

Think about whether it's possible that any dangerous user input code can get into the areas you call with raw() or html_safe()

How to destroy every instance of a certain ActiveRecord backed moel in the database? (e.g. Topic models)

Topic.destroy_all

"When figuring out what to test, ask"

What level of assurance is needed - will someone lose money / their life - or will they just have to fill in a web form again? e.g. Twitter lost tweets at first and only got reliable eventually - no-one will care that much if they lose a tweet

rails - when :remote => true what kind of request is sent

XMLHttpRequest (instead of regular HTTP request)

User has_many habits(:dependent => :destroy) and Habit has_many results(:dependent => :destroy) Will destroying a user wipe its results?

Yes it will

if you are going to monkey patch a gem you should put that code in

a Rails.root/lib/patches directory and then require it within the initializer # putting it in a patches directory makes it clear to later readers of your code

"in order to use belongs_to in a class, that class must have...."

a foreign_key

rails - what does asset_data_uri do #logo { background: url(<%= asset_data_uri 'logo.png' %>) }

a method of embedding the image data directly into the CSS file €" you can use the asset_data_uri helper.

rails 3.1 - where should you store your images?

assets/images

which is generally preferred: rss or atom

atom

rails - if a controller won't assign a variable with ease what is most likely wrong

attr isn't accessible

rails - if you cannot set up an association by specifiying attributes in the new method what might be wrong e.g. Locale.new(:keyword => keyword)

attr_accessible not open for :keyword

rails - accepts_nested_attributes_for :author creates what method

author_attributes=(attributes)

rails - two callbacks that occur before before_save

before_validation after_validation

rails - is before_validation called before or after before_save

before_validation is called before before_save

"why use: caches_action :index, :show over normal: cache_page :public"

cache_action allows filters to be run before - e.g. for authentication

How to send email in development mode

config.action_mailer.delivery_method = :sendmail # or config.action_mailer.delivery_method = :smtp

how to get production errors showing locally (when running production mode)

class ActionDispatch::Request def local? false end end in production.rb file

active record (models) how to have a Customer inherit from Person

class Person < ActiveRecord::Base end class Customer < Person has_many :orders end

rails 3.1 - how to do ssl in one particular controller

class PostController force_ssl # accepts only/except to filter actions that the ssl applies to

difference between time and datetime in ActiveRecord::Base

datetime is time and date time is time only

rails - rspec won't run... first port of call?

db probably isn't created. try rake db:test:clone

where does the seeds.rb file go?

db/

rails 3.1 - up and down migration methods have been swapped for

def change # if you have something irreversible to migrate switch to def up and def down

"fix the stack level too deep error here where display_name is a database attribute and the current object, self, is subclassed from ActiveRecord::Base def display_name display_name || full_name end"

def display_name read_attribute(:display_name) || full_name end

rails - get this action to create an etag def show @product = Product.find(params[:id]) end

def show @product = Product.find(params[:id]) fresh_when etag: @product end

rails - what does the except do Post.order('id asc').except(:order)

discards the order condition

rails - with long running migrations where you modify data you should....

either split it into smaller steps or log changes as it goes (otherwise you are waiting a half hour to see if it worked)

if you have your controller namespaced into facebook_app (e.g. in an engine) what needs to be in your routes

either: namespace :facebook_app # if you want /facebook_app in front of every url or scope(:module => :facebook_app) # if you want to access it without prepending facebook_app to the url

rails - a rails application is a type of

engine

rails 3.2 -- how to get etag and last_modified set at once

fresh_when @product

Rails - env[ €˜QUERY_STRING €™] is set only when the request is sent as a

get

"why should you not use complex finders in controllers e.g. def index @published_posts = Post.find(:all, :conditions => { :state => 'published' }, :limit => 10, :order => 'created_at desc') end"

hard to maintain (what if we had this logic in 10 different places and then you change what you want to count appear as a published_post... you need to change each controller) # prefer scopes... such as Post.published_posts

if you want ActionMailer methods to send a plain email and a html email AT THE SAME TIME what must you do

have two separate views welcome.text.erb welcome.html.erb

how to call a helper method in the rails console

helper.method

Besides regular views where else do you need to watch for XSS?

in flash[:notice] e.g. flash[:notice] = #{params[:user][:username]}

"when your rails app stalls on save and there are no obvious errors in the logs, what could be up?"

infinite recursion with model callbacks e.g. after_committer :do_something def do_something .. save end

shortest way to test associations

it { respond_to?(:addresses) }

rails - does ActiveRecord::Base#reload get new data from db or reload whole object

just data from db

rails - try(:disabled) .. does this work for local_variables as well as methods

just methods

rails 3.1 besides app/assets where else can you put javascripts and images

lib/assets vendor/assets #use these when there are assets not specific to your application.

how to link to a photo using resourceful routes (but when you only have the photo's id)

link_to photo_path(id)

how to use an engine url helper

my_engine.root_url my_engine.product_path(@product) # etc.

check if an ActiveRecord::Base object is saved

mymodel.persisted?

you've already called project.milestones (fetching the data from the database) will projects.milestones.empty? hit the database a second time

no - Rails caches the result and subsequent calls to .milestones refer to this

rails is this right? form_tag do |f|

no - form_tag does not take a block variable (|f| here). Example: form_tag do radio_button_tag # instead of f.radio_button_tag end

you've already run project.milestones (to fetch from db) will projects.milestones.size hit the db?

no - it hits the cache

How to view the errors on a particular attribute when a validation fails on an ActiveRecord model

object.errors[:name]

rails - accepts_nested_attributes_for - at what point do changes occur

on save of the parent model

rails - expire_fragment('all_available_products') where can this be used?

only in controllers

"which one of the following scopes will allow builder conditions to be called on it scope :titled_luda, where(:title => 'Luda') OR where(""title = 'Luda'"")"

only the first one (hash notation) Post.titled_luda.build

"rails - how to get truncate to add ""...(continued)"" to the end of oversized strings"

option :omission => '... (continued)'

what can screw up styles in rails 3.1 css

order of css files - add dependencies like yui before adding files which use these dependencies e.g. being application.css with // require yui-4.3.1

disadvantage of using Memstore to store action_caches

problem is not shared between processes

rails has_and_belongs_to_many :associated_objects how to remove associations without deleting original items

product.associate_objects.clear

match 'products/recent' what named route will this give

products_recent

whats the minimum you need to do reload a gem on your path (i.e. that you are developing) in rails console

quit and restart console.

rails - generate a secure secret

rake secret

quick way to check (within a Rails application) that the request was a get

request.get?

"Rails - code to get the host domain name from within a controller ""Google"""

request.host

how to get the remote ip of a request

request.remote_ip

find out current url in rails

request.url

how to get current url in rails

request.url # http://www.mysite.com/current_page

rails 3.1 - asset pipeline - require assets in the current directory but not sub-directories # desired application.js posts.js # not desired admin/dash.js

require_directory .

rails - what does this file do inside the assets pipeline js file //= require_tree ../templates

requires every file in ../templates or app/assets/templates

in rails what does Hash#except do?

return a hash than includes everything but the given keys e.g. params[:person].except(:admin)

acts_likes_date? (RAILS only)

returns t/f enabling better duck typing on date like classes

what does :dependent => :restrict do in a has many collection

stops the object from being deleted if it has an associated object

Rails - params.keys returns an array of what?

strings

Rails nested resources: notes_pack/4/subject/10 which is params[:id] - notes_pack or subject

subject... i.e. the nested resource subject id = params[:id] notes_pack id= params[:notes_pack_id]

rails - what to watch out for in queries that search for nils

that you are aware that in sql null and false are completely different # or there may be a set of falses in the test data (due to migration default) and a set of nils in your real app (due to default not being set on your existing data)

how does rails determine the correct response format (JSON etc.)

the HTTP Accept header submitted by the client

rails - when adding new attributes to a model (e.g. via a migration) don't forget to update

the attr_accessible whitelist/blacklist

logs say this Rendered devise/registrations/new.html.haml within layouts/application (98.7ms) yet you see nothing...

the files must be blank

"in a has one / belongs_to relation, which model has the key"

the model in which you declare belongs_to

"rails - when to use notifications like this ActiveSupport::Notifications.instrument(""products.search"", :search => search)"

to do something outside core logic of app (e.g. to save page request times to a log) Core tasks like sending an email to a user is not an acceptable use of notifications.

Rails - what is the purpose of the application.rb

to load all the required dependencies and configure the application e.g. require 'pdf_render' #where pdf_render was added to load_path in boot.rb

when extracting an app into an engine what to watch out for with the tables

to namespace them .. e.g. if you have a user model in a forum engine the table ought to be called forum_users

"rails - why do caches_action :show, :layout => false"

to render the page's content but let the layout be rendered dynamically

rails - really bad move with rake db:rollback

to run it when not necessary # I accidentally deleted useful columns filled with data on a long running scraper once

when using selenium what must you be aware of re: Rails data

transactional features will not work => fix with database cleaner gem # Transactional fixtures make Selenium an unhappy camper config.use_transactional_fixtures = false config.before do if example.metadata[:js] DatabaseCleaner.strategy = :truncation else DatabaseCleaner.strategy = :transaction end DatabaseCleaner.start end config.after do DatabaseCleaner.clean end

"a user has_many orders, how to get the number of orders on a user quickly"

user.orders.count

rails scaffold user:reference or user:references

user:references PLURAL

rails - why use link_to in block syntax like the following: <%= link_to(@profile) do %> <strong><%= @profile.name %></strong> -- <span>Check it out!</span> <% end %>

when it's difficult to fit the style you want for the link text into the normal syntax

rails -- when is this a bad way to generate an etag fresh_when etag: @product

when the dynamic content on the page depends on more than the product (since the product's updated_at field is used to generated the etag)

rails - when is last_modified preferable to etag

whenever it lets you subsitute an otherwise costly database call e.g. def index @products = Product.scoped #defers enumerating with .all until in view fresh_when last_modified: @products.maximum(:updated_at) end

"Can you call scopes on associations e.g. product.properties.with_name(""year"")"

yep

"can a compound index with [item_id, item_type, item_pos] be used as an index for item_id and item_type compound query?"

yes

"can a compound index with [item_id, item_type, item_pos] be used as an index for item_id?"

yes

"rails - can you set an author association with author_id foreign key with the following code: Lead.create(:username => ""jack"", :author_id => 4)"

yes

"rails - if you have a coffee file with the same name as your controller action (and a blank controller action), will the coffee file render"

yes

does .present? return false for an empty array

yes

rails - get rid of white space in front of and after a string

String#squish

how to make AR where hash notation use and SQL BETWEEN operator

Student.where(:grade => 1..6)

If your Rails views don't make sense what should you try

clearing the cache

collection_select? association OR association_id

".collection_select :hooker_id,"

how to assign a variable @post so it's accessible in a partial as the local variable 'post' ?

"<%= render ""sidebar"", :locals => {:post => @post} %>"

how to change a column name in rails migrations

"rename_column :users, :name, :first_name"

how to remove html tags from a string in Rails

"strip_tags(""<p>hi</p>"") => ""Hi"""

Do you need to restart the server for new routes to work?

No - routes are updated instantaneously in development mode by default.

rails - give an example of dynamic scopes

Product.scoped_by_price(4.99) #generated based on attributes of model # can even use and

"get the table name in ActiveRecord::Base given a subclass, Product"

Product.send :compute_table_name

What does profiling mode do in performance testing?

Provides an in-depth pic of the slow parts on the code.

How to create a database in the test env

RAILS_ENV=test rake db:create

how to create the test database (with Rake)

RAILS_ENV=test rake db:create

Rails.production? or Rails.env.production?

Rails.env.production?

pretty way to test whether current Rails environment is production

Rails.env.production?

what's wrong with putting Rails.root before require 'rails/all'

Rails.root won't be defined at this point -- use relative paths instead require '../config.yml' for example

why is it important to share asset compile folders between deployments?

So that remotely cached pages that reference the old compiled assets still work for the life of the cached page

rails - find all students who have a school with type attribute public student has_many :schools

Student.joins(:schools).where(:schools => { :type => 'public' })

rails - if an asset name is misspelled in a manifest file what happens

The page won't load in browser (alerting you to the problem)

what does cross site forgery protection do?

adds a unique session token field to all forms that is checked on every non-GET request.

rails 3.1 where to put js and stylesheets

app/assets

rails - button that calls a js function

"button_to_function ""hi"", ""alert('hi')"""

"rails - how to get distinct posts in this counter operation Post.count(:joins => :seller, :group => :seller_id)"

:distinct => true # turns into the sql: SELECT COUNT(DISTINCT posts.id)

what determines whether form_for(@post) does a post or put request

ActiveRecord::Base#persisted? response

How configure Rails so that models will automatically have mass assignment disabled until they have it explicitly enabled by attr_accessible.

ActiveRecord::Base.attr_accessible(nil)

Whenever you are pushing code to the server what must you also remember to do

Run any new migrations on the server # or better yet write a script that automates the whole lot

rails 3.2 - what does the following do: Event.where(created_at: Time.now.all_week)

Time#all_day/week/quarter/year as a way of generating temporal ranges and where accepting ranges

rails - what is this error? ActiveRecord::StatementInvalid (PG::Error: SSL error: decryption failed or bad record )

Usually happens because postgres expects SSL despite SSL not being used turn it off set ssl=false in postgresql.conf (and restart the db server)

"belongs_to :author, :counter_cache => true what does this do?"

caches num of belonging on associate class (author)

rails - reference previous state of database column (e.g. description)

description_was

why won't code in a migration which modifies the data sometimes work

if it references a column which is only brought into existence by that migration # Product.reset_column_information called after the new columns have been added will fix this issue

why is this a good name for a module: module User::AuctionConcerns

since it explains that these are the user's auction related methods

"what's wrong with this .js view $('#foo-list').css('background', 'yellow').html(<%= escape_javascript(render('foo')) %>);"

"# need to wrap rendered stuff from ruby in quotation marks $('#foo-list').css('background', 'yellow').html(""<%= escape_javascript(render('foo')) %>"");"

rails - flash info about an exception in a view

"# notice how the rescue method gets passed a parameter with the error rescue_from FbGraph::Exception, :with => :fb_graph_exception def fb_graph_exception(e) flash[:error] = { :title => e.class, :message => e.message } end"

in helper methods how do you display html

"# option1) put it in quotation marks ""<li>"" or %Q{<li>} # option2) use tag() tag(""input"", :type => 'text', :disabled => true)"

How to enforce that a migration is irreversible

"# raise an error when someone tries to migrate down def self.down raise IrreversibleMigration ""Salts are a one way road."" end"

how to rescue from most server errors in Rails

"# rescue an exceptions that is high up the exception error chain rescue_from StandardError, :with => :internal_server_json_error # other examples: # rescue_from Exception for higher again # rescue_from NoMethodError for more specific"

rails - how to deal with complicated sql statements so they look nice

"# split them into an array of small strings and then call join has_many :purchases, :finder_sql => [""purchases.user_id = plays.user_id"", ""and purchases.auction_id = plays.auction_id"", ""and purchases.confirmed = ?""].join(' ')"

rails - how to do a redirect where you run code to modify a param

"# supply redirect with a block where the first argument represents the params match '/t/subjects/*id' => redirect {|params| ""/t/products/#{params[:id].split(""/"").last}"" }"

testing (webmock gem) - how to stub request to any url on facebook

"# use a regex for the request WebMock.stub_request(:get, %r{https://graph.facebook.com/}).to_return(status: 200, body: {id: 123}.to_json)"

if you want to render a collection as a series of partials what is the most concise way

"# use the :collection option render :partial => ""/grind/micro_profile"", :collection => @grinds"

write a scope to find users with orders which have at least two line items # a user has_many orders and an order has_many line_items

"# user class scope :min_2_items, joins(:orders => :line_items). # get access to right data in db with joins group('users.id'). # you only want the unique users having('COUNT(line_items.id) >= 2') # action performed on the groups"

"rails - get this to scope to work in the case where state_and_following_states is defined later in the file scope :installed, where(:state => state_and_following_states(""installed""))"

"# wrap the method in a lambda, since otherwise it is called straight away and will give issues if state_and_following_states is defined further down the file scope :installed, lambda { where(:state => state_and_following_states(""installed"")) }"

You already have a scope called :published Write a scope :recent that returns an ordered list of published articles

"# you can call other scopes you have already defined within your scopes scope :recent, published.order(""posts.published_at DESC"")"

rails - gotcha with relationship between attr_accessible and accepts_nested_attributes_for

"#need to update attr_accessible when using nested_attributes_for attr_accessible :name, :posts_attributes"

rails - update every item in an active record relation

"#update_all Conversion.where(:state => :generated_infographic).update_all(:state => ""installed"")"

How to link to an image in rails

"#use regular link_to but instead of text have an image_tag <%= link_to image_tag(""search.gif""), search_path %>"

how to use ruby in coffeescript

"$('#logo').attr src: ""<%= asset_path('logo.png') %>"""

why drive out view implementation with rspec

"(learn what models and controllers needed) -- views are the final clients of your objects -- by starting with them we really write the code we wish we had first, driving excellent api design"

when should you include a railtie in your gem

"* Your gem needs to perform a given task while or after the Rails application is initialized; €¢ Your gem needs to change a conï¬Åguration value, like setting a generator;"

how to load assets from an engine in rails

"//= require your_engine_name If you have split your js in different files, your file your_engine_name/app/assets/javascripts/your_engine_name.js could have the following: //= require_tree ."

how to use a debugger inside the rails app

"1) add ruby-debug to gemfile 2) start server with debugger r s --debugger 3) put ""debugger"" at point in your code when you want to start debugging"

how to ask a confirmation question on a button / link in rails

":confirm => ""Are you sure you want to delete #{@subject.name}?|"

How are nested model parameters passed from a field_for?

":model => {:attr => """", :nested_model_attributes => {} } Note the addition of the word ""attributes"" to the nested model hash key"

syntax to create a simple rack application in rails 3 routes

":to => proc {|env| [status_code, {headers_hash}, [""body content""] ]} e.g . :to => proc {|env| [200, {}, [""Welcome""] ]}"

how to get rails fragment caching to refresh every hour

"<% cache(""top_products"", :expires_in => 1.hour) do %>"

What command is used change a column data type in rails migrations

"change_column :users, :date, :datetime"

how to do fragment caching in rails

"<% cache(product) do %> <div><%= link_to product, product.name %>: <%= product.price%></div> <div><%= do_something_complicated%></div> <% end %> #note that rails will create a unique key for each active record object"

helper to conditionally link (e.g. link to a user page provided the message object has a non-false user)

"<%= link_to_if message.user, 'Poster', user_path(message.user) %>"

rails - how to do select tags

"<%= select(:conversion_state, POSSIBLE_STATES_ARRAY) %>"

rails - rewrite this in a way easier to make dynamic <%= text_field_tag :name %>

"<%= text_field_tag ""name"" %> now you can modify it to be: <%= text_field_tag ""name_#{n} %>"

"rails - how to get params nested like this with text_filed_tag {""controller"" => ""bla"", ""split_instructions"" => {""1"" => {""name"" => ""value"" }"

"<%= text_field_tag ""split_instructions[#{n}][name]"" %>"

What would you add to a form (spoofing a request) to set the User.role_id column to 1

"<input type=""text"" name=""user[role_id]"" value=""1""/>"

how to link to back

"= link_to ""Back to search results"", :back"

"[""a"", ""1b"", ""ascv"", ""1234""].sort give what"

"=> [""a"", ""1b"", ""ascv"", ""1234""] i.e. smallest to biggest"

rails - execute raw sql in Rails console

"> sql = ""update records set id=43 where id=44"" >> ActiveRecord::Base.connection.execute(sql)"

set all the attributes of an active record instance at once by passing a hash

"@user.attributes = { :username => 'Phusion', :is_admin => true }"

rails 3.1 - what ActiveRecord::Base methods accept a second hash specifying role for assigning attributes

"ActiveRecord::Base#new, ActiveRecord::Base#create and ActiveRecord::Base#update_attributes Post.new(params[:post], :as => :admin)"

rails - how to send a notification called products.search with payload[:search] available

"ActiveSupport::Notifications.instrument(""products.search"", :search => search)"

Give an example of a good place to use find_or_create_by_attr(attr)

"Anywhere where you don't want duplicate listings => geocoded locations, category groupings"

Rails if you want the input of a method to always be an array (even if a single object passed in)

"Array.wrap(1) => [1] Array.wrap([1,2,3]) => [1,2,3]"

"fix this: Article.first.order(""published_at desc"")"

"Artice.order(""published_at desc"").first # reasoning: the code in the question just got the first item (using a non specified order) and then ordered this result. What you really want is to get the first of the ordered lot"

rails - technique for including javascript only on a certain view

"Include the javscript in a content_for :head block and then yield that block in your application layout. # view <% content_for :on_page_js do %> <script type=""text/javascript""> <%= render :partial => ""my_view_javascript"" %> </script> <% end %> </script> <% end %> # layout <%= yield :on_page_js %>"

Rails - count ... how to join to another table

"JobTitle.count(:joins => :seniority, :where => ""seniority.level > 3"")"

"rails - how to create a join model (i.e. the through model) in one line models: Locale, Keyword, KeywordLocale"

"KeywordLocale.create({:keyword => keyword, :locale => locale}) # assuming attr_accessible keyword, locale"

why should you never use the Rails default routes? map.connect ':controller/:action/:id' map.connect ':controller/:action/:id.:format'

"Leaving the defaults open leads to problems because users can create, update or destroy a post with GET. If you have a model, say posts, as a resource, then this means users can only create a post by using HTTP POST, update a post with PUT and destroy a post by DELETE. Doing so gives you excellent security checks."

"how to store a hash/array in db for an ActiveRecord object e.g. :preferences => { ""background"" => ""black"", ""display"" => large }"

"Model definition serialize :preferences NOW User.create(:preferences => { ""background"" => ""black"", ""display"" => large }) works"

how to get a true or false for whether or not a model exists in rails

"Model.exists?(id) # you can also specify conditions Person.exists?(:name => ""David"")"

How to create an ActiveRecord finder that checks for created_at in the last week

"Model.where(""created_at > '#{1.week.ago}'"") essentially a condition with time_col_name > 'time' # remember you can interpolate ruby code into a condition # also remember that you need inverted commas (inside the outer quotation parts) around the date itself"

First step for making your password storage secure

"Not only do you limit access to DB but you don't store passwords per se, but rather an encrypted version of them (digests)"

compute the minimum for a Model's column

"Person.minimum(""age"")"

rails - manually inspect a cache entry for christian-ethics-product-data

"Rails.cache.read ""christian-ethics-notes_product_data"""

Performance reason to use unit tests most?

"Since, if done correctly, they don't require much hardware resources to run"

what routes will this match match 'photos/*other' => 'photos#unknown'

"This route would match any route with photos/something at the end. e.g. photos/12 or /photos/long/path/to/12, setting params[:other] to ""12"" or ""long/path/to/12""."

"rails 3.2 - first_or_create, first_or_create!, first_or_initialize were added give an example of first_or_create!"

"User.where(:first_name => ""Scarlett"").first_or_create!(:last_name => ""Johansson"") # notice the way a hash is provided"

why should you think twice about tableless rails models

"often good to have data for backup, delayed jobs and analysis"

you want a custom time format in rails. where do you define it?

"add a lambda to Time::DATE_FORMATS # example: initializers/time_format.rb Time::DATE_FORMATS[:email] = lambda { |time| time.strftime(""%a, %B #{ActiveSupport::Inflector.ordinalize(time.day)}, %Y"") }"

syntax for creating a compound index in migrations

"add_index :conversations, [:created_at, :language_code] # used when you are querying by both fields at once"

in rack what does the run method take as a param

"anything that responds to a call (a Proc, a lambda, a class's methods)"

in thor you do you put text at the bottom of the file

"append_file 'config/environments/test.rb' do 'config.gem ""rspec""' end"

rails - what should you store in session

"as little as possible since it may be seen by user in CookieStore and maybe manipulated using replay attacks (saving the state of a cookie detailing credits count before he spends them, then reverting back to the state of the cookie with the unspent credits, thus tricking your system)"

rails 3.2 - set_table_name is deprecated... what is used instead:

"assignment methods class Project < ActiveRecord::Base self.table_name = ""project"" end"

"<%= render ""shared/header"", :my_title_text => ""Welcome"" %> does what"

"assigns <%= my_title_text %> in the partial to ""welcome"""

"why is this wrong (you have an engine called FacebookApp) mount FacebookApp => ""/"""

"because FacebookApp is a module; it isn't a rack application (and mount expects a rack application as its argument) do this instead mount FacebookApp::Engine => ""/"""

"why would you need a class name like this: module Billing class Account < ActiveRecord::Base belongs_to :firm, :class_name => ""MyApplication::Business::Firm"" end"

"because associations only look for objects within the current module scope thus the full name (including app name, and modules) is need for it to find the class(which is the last part in the full name) ""MyApplication::Business::Firm"""

"why won't this work (socialite_awards is a has_many wrapper around awards with added conditions) has_many :socialite_awards, :conditions => ""award.name = ""socialite"" class Award end"

"because it is missing a class name has_many :socialite_awards, :class_name => ""Award"", :conditions => ""award.name = ""socialite"""

rails - why does render sometimes fail to find a present file

"because it's looking for a partial and you are trying to render a full file. when stuck try this instead: render(:file => ""photos/new"")"

"why does modifying the habits here return a readonly error when your scope is like this scope :with_habits, joins(:habits)"

"because joins are read only. get past with scope :with_habits, joins(:habits).select(""users.*"")"

Product has an is_an_all_notes_pack attr LineItem.joins(:product).where(:is_an_all_notes_pack => false).to_a why won't this work?

"because that form of where clause assumes the column (is_an_all_notes_pack) is on the calling model (LineItem) this will work instead LineItem.joins(:product).where(""products.is_an_all_notes_pack is null"").to_a better yet: create a scope in the product model - .all_notes_pack"

"you want to delete orders created in the past 2 minutes why is this very wrong Order.where(""created_at < ?"", 2.minutes.ago).destroy_all"

"because the 2.minutes ago is converted to an absolute time and in fact this does the opposite of our intention and destroy all users created_at except those created in the last two minutes instead Order.where(""created_at > ?"", 2.minutes.ago).destroy_all"

difference between before_create and before_save

"before_create only called when a new object is saved, before_save called on every save of that object (including the one for creation)"

you want to have blog.author although the other class is actually User. How

"belongs_to :author, :class_name => :user"

specify that your model is polymorphic (and that it's associated object is a commentable)

"belongs_to :commentable, :polymorphic => true"

how to make the associated objects validated when parent object saved

"belongs_to :parent, :validate => true"

how to make an associated object read only through the association

"belongs_to :user, :readonly => true"

how to update an associated object's updated_at attributes automagically every time the parent record is saved/ destroyed

"belongs_to :user, :touch => true"

"rails - how to get only certain values from a hash (e.g. getting only the ""username"" and ""gender"" from big_hash)"

"big_hash.slice(""username"", ""gender"")"

rails - strategy to test a gem which modifies rails itself

"build a dummy app in gem, and use tests which look at the funcionality of the gem (in the context of this dummy app) #e.g. building a contact form - use the code in your dummy app and test with functionality in integration tests"

with scopes you can invoke all the ..... .... and ... methods on a relation

"builder, update and destroy methods e.g. Post.titled_luda.build Post.published.update_all(""views_count = views_count + 1"") Post.unpublished.destroy_all"

"what is wrong with this =f.buttons do - f.commit_button ""Send Sms"""

"button won't display need = f.commit_button ""Send Sms"""

rails - where are action caches stored

"cache_store -- which might be memcached, the ruby process running the app (MemoryStore) or something else you've set."

cache the index action only if the format requested is JSON

"caches_action :index, :if => proc do |c| !c.request.format.json? # cache if is not a JSON request end"

If you want to activate caching for certain actions in a controller

"caches_page :index, :help, :home, :faq # assumes caching is enabled in your enviroment"

if active record is not assigning attributes to an a-ok model right what super dumb mistake have you made

"calling a column ""type"" a reserved keyword"

code you would put in application controller to rescue from a custom exception (e.g. AccessDenied)

"class ApplicationController < ActionController::Base rescue_from AccessDenied, :with => :access_denied protected def access_denied redirect_to ""/401.html"" end end"

how to specifically set a custom table name in an ActiveRecord model (e.g. when pluralization might be hard)

"class Mouse < ActiveRecord::Base set_table_name ""mice"" end # rails 3.2 it changes: self.table_name ="

"rails - refactor this to use an observer class Project < ActiveRecord::Base after_create :send_create_notifications private def send_create_notifications members.each do |member| ProjectMailer.deliver_notification(self, member) end end end"

"class Project < ActiveRecord::Base # nothing here end class NotificationObserver < ActiveRecord::Observer observe Project def after_create(project) project.members.each do |member| ProjectMailer.deliver_notice(project, member) end end end"

how to use respond_to in rails to only give html to the index

"class UsersController < ApplicationController::Base respond_to :html, :only => :index end"

you can call what kind of methods on named scopes?

"class methods (self.method_name) you can also call methods defined within extensions scope :new lambda {where(""posts.created_at > ?"", 1.day.ago) } do def my_extension_method end end"

"which is correct belongs_to :author, :class_name => NotesPack belongs_to :author, :class _name=> ""NotesPack"""

"class_name must be quoted belongs_to :author, :class _name=> ""NotesPack"""

rails js/erb fix this: click_anywhere_redirect(<%= Rails.application.routes.url_helpers.root_path %>)

"click_anywhere_redirect(""<%= Rails.application.routes.url_helpers.root_path %>"")"

for every Post you call the (associated) author.name and (associated) comments.body Optimise this query using ActiveRecord includes

"comma separated symbols Post.includes(:author, :comments)"

what is the purpose of the asset pipeline

"concatenate (turn into one file) and minify js and css assets, and allow developers to write these assets in many languages like sass and erb"

rails - how to set a directory for cache files to go in?

"config.action_controller.page_cache_directory = File.join(Rails.root, 'public', 'cache') # note that your local webrick server will not find cache if it isn't in the default /public folder"

rails - add folder with additional types of assets so helpers can reach them (flash)

"config.assets.paths << Rails.root.join(""app"", ""assets"", ""flash"") # application.rb"

tell rails to autoload files in lib directory

"config.autoload_paths += %W( #{config.root}/lib ) #NOTE to load a class/module it must have the same name as the file (e.g. class Exceptions in exceptions.rb will load, but not class ZeroError in same file)"

how to change the default test framework and fixture for generators in rails

"config.generators do |g| g.test_framework :rspec, :fixture_replacement => :factory_girl"

rails - route level how to build an API

"constraints :subdomain => ""api"" do scope :module => ""api"", :as => ""api"" do resource ""products"" end end"

one liner for setting content for title in a view

"content_for :title, @post.title"

"how to use content_tag to create the following: <div class=""strong""><p>Hello world!</p></div>"

"content_tag(:div, content_tag(:p, ""Hello world!""), :class => ""strong"")"

"what's wrong with this in a controller spec post :successfully_completed_today, :id =>1"

"controller specs don't lke integers -- give it a string instead post :successfully_completed_today, :id =>""1"""

what does this rails helper return (1..5).index_by {|n| n*10}

"converts the collection into a hash where keys are values returned by a block # => {50=>5, 40=>4, 30=>3, 20=>2, 10=>1}"

what should this be cookies[:conversion_id] = nil

"cookies.delete(:conversion_id) #why? because in the first case you just set :conversion_id to """", which isn't ideal"

rails - make a cookie secure

"cookies[:stuff, :secure => true] = ""my name is jack"" # force_ssl automatically makes all cookies secure"

capybara - how to ensure page has 2 elements of a particular type?

"count option page.has_css?(""div.records li"", :count => 2)"

what does create_file do (THOR)

"create_file ""filename"" do contents end creates a file with data (given in block)"

"what's the path here: namespace :api do resources :subjects, :only => [] do post :create_products, :on => :member end end"

"create_products_api_subject_path i.e. the member part first, then namespace then the resource"

how to force a migration to recreate a table (e.g. you want to create a table again from scratch)

"create_table ""courses"", :force => true do |t|"

rails - what does .to_xml do?

"creates an xml document to represent the model <topic> <title> Topic 1 </title> <author-name> Jack </author-name> etc, every attribute present"

modify this code to be a working rails validator hint: error is on base def at_least_one_notes_file notes_files.size < 1 end

"def at_least_one_notes_file if notes_files.size < 1 errors[:base] << ""You need to add at least one file for the upload to work"" end end"

how to use hash notation with rails3 where clause

"def authenticate(user_name,password) where(:user_name => user_name, :password => password) end"

Give an example of a yield helper

"def if_logged_in yield if logged_in? end <% if_logged_in do %> <%= link_to ""logout"" %> <% end %>"

how to get a rails action to respond to a request with nothing (e.g. tracking)

"def liked_on_fb bingo!(""liked_on_fb"") render :nothing => true end"

"rails - what is the cache_path option used for? example code: caches_action :new, :cache_path => ""sellers/new"""

"if multiple routes go to the same action, you only want one cache"

rails - simple way to cache a page with http caching

"def show response.headers['Cache-Control'] = 'public, max-age=300' end # If you want to cache entire pages on Heroku do the above since Varnish caches content with Cache-Control headers # you can put something like that in a before_filter"

rails 3 preferred way to do date formats

"define your format in your en.yml file en: date: formats: article: ""%d %B, %Y"" call with <%= l(blog_post.published_at.to_date, :format => :article) %>"

Whats the right amount of test coverage ?

"depends on the app - sometimes there is no way you can fail (finance apps, government apps to determine IP space) in which case you'll need to test massively - but other times much less is necessary (e.g.a small startup/experiment to see if there is market interest doesn't need to be bullet proof)"

rails - how to avoid DDOS attacks from uploads

"do uploads asynchronously - otherwise a malicious user will upload many large files from numerous machines at once, taking down your server's capacity to deal with new requests"

"rails - what is wrong with this code to update the params params[:seller].merge({""buy_out"" => ""1""}) do_something_using_updated_params(params)"

"doesn't change params you need params[:seller].merge!({""buy_out"" => ""1""}) do_something_using_updated_params(params)"

rails 3.1 - link to a subdomain

"edit_project_url(..., :subdomain => ""foo"")"

"Rails - how to get a reference to an email without sending it (assume Notifier class, contact method)"

"email = Notifier.contact(""[email protected]"") #now you can do tests like: assert_equal 2, email.parts.size assert_equal ""multipart/alternative"", email.mime_type"

rails - how to get asset to rails asset helpers in javascript files

"embedded erb $('#logo').attr({ src: ""<%= asset_path('logo.png') %>"" });"

in custom validations what is the second param of errors.add()

"errors.add(..., ""message to be shown"")"

in custom validations what is the first param of errors.add()

"errors.add(:attr_name, ...)"

because there is a limit to how much you can store in session (due to cookies specification in HTTP) what can you do

"exclude certain parts (big unnecessary ones) session[:auth] =onminauth.except(""extra"")"

rails - how to expire five diff methods on a controller cache

"expire_page(:controller => ""pages"", :action => %w( sellers_faq, describe_notes_tips, about_us, terms, home))"

rails forms -- select between two values for sex

"f.select :sex, [""Male"", ""Female""]"

How to fight slow test suites (3 options)

"faster machine, profiler to identify and examine slow tests, stop hitting external services"

"belongs_to :favorite_person, :class_name => ""Person"" uses what as its foreign key?"

"favourite_person_id change using :foreign_key => ""Person"""

there is no excuse for not indexing on ....

"foreign keys e.g. add_index :conversations, :user_id"

typically what database columns need to be indexed?

"foreign keys, anything used in a ""group by"" statement, cols that need to be sorted, or searched on in any way (along a where statement)"

when to use form_for vs form_tag

"form_for, to interact with a defined object model. All those ones ending in _tag are for unbound forms. e.g. search form is usually an unbound form"

rails -- how to set http cache-control to public

"fresh_when @product, public: true"

in templates how to specify gems only work in certain envs

"gem ""shoulda"", :group => :test"

how to specify a particular branch in bundler (e.g. when taking from git)

"gem ""sphinx"", :git => ""giturl"", :branch => ""rails3"""

how to get ruby debug for ruby19 and 18 in one gemfile

"gem 'ruby-debug19', :require => 'ruby-debug', :platforms => :mri_19 gem 'ruby-debug', :platforms => :mri_18"

how to specify conditions for an association (i.e. has_many approved comments)

"give the association a special name, then a class_name and conditions options has_many :approved_comments, :class_name => 'Comment', :conditions => ['approved = ?', true]"

set the default order on a has_and_belongs_to_many relationship

"habtm :tags, :order => {}"

how to customize the join table name on a habtm relationship

"has_and_belongs_to_many :categories, :join_table => ""prods_cats"""

rails - how to add certain conditions to a has_many method

"has_many :accepted_applications, :conditions => {:status => 'accepted'}"

how to run a method straight after adding an association object

"has_many :comments, :after_add => :method_name"

how to call a method straight after deleting an association

"has_many :comments, :after_remove => :method_name"

you have a polymorphic Comment model that refers to its association as commentable. What code goes in an Article model to associate a comment?

"has_many :comments, :as => :commentable"

how to run a method before adding an association object

"has_many :comments, :before_add => :method_name"

how to run a method before deleting an association

"has_many :comments, :before_remove => :method_name"

"how to highlight the phrase ""rails"" in ""you searched for rails"" in rails"

"highlight(""you searched for rails"", ""rails"") adds a class <strong class=""highlight""> around the rails text"

how to ensure all associated objects are destroyed alongside the current object (using destroy method)

"hm :comments, :dependent => :destroy"

rails - get the image path (not an img html tag as returned by standard image_tag() )

"image_path(""edit.png"")"

"besides needing to use ""x_url"" over ""x_path"" in ActionMailer views, what other major difference is there between links in mailer views and normal HTML views?"

"in mailers you need to specify a host param with each url <%= url_for(:host => ""example.com"", :controller => ""welcome"", :action => ""greeting"") %> # or fix it globally with: default_url_options[:host] = ""example.com"""

Your engine's routes are not showing after you include the engine into your app with a gem. What should you do?

"in routes.rb of main app mount MyEngine::Engine => ""/blog"""

"what does this class method do Habit.increment_counter(counter_col_name, id_of_object)"

"increments a column by 1 AND SAVES e.g. Habit.increment_counter(:successful_days_count, 72)"

"a model in rails has this attribute: calculable_type: ""ShippingMethod"" what does this tell you?"

"it has a polymorphic association, calculable"

"rails - what is wrong with this route match ""/unsubscribe#send_email"""

"it should be match ""/unsubscribe/send_email"""

rails -- how to limit length of string in migrations for db (EFFICIENCY INCREASE)

"limit param t.string, :login, :limit => 10"

"pass a name parameter of ""jack"" to babysitters_path"

"link_to babysitters_path(:name=>""jack"")"

"how to use mail_to to replace @ with ""at"" and encode with hex"

"mail_to ""[email protected]:, :encode => ""hex"", :replace_at => ""at"", :replace_dot => ""_dot_"""

rails - how to delete cache outside of controllers (e.g. if you have asynchronous stuff)

"manually - Rails.cache.delete(""#{product.permalink}_product_data"")"

how to do redirects in rails 3 routes

"match ""/about"" => redirect(""/aboutus"") # where match ""/aboutus"" exists"

rails - apply a default 'jpg' :format param to this route match 'photos/:id' => 'photos#show'

"match 'photos/:id' => 'photos#show', :defaults => { :format => 'jpg' }"

"rails routes - enforce that the param match a regex match 'photos/:id' => 'photos#show',"

"match 'photos/:id' => 'photos#show', :id => /[A-Z]\d{5}/"

"rails - permit more than one verb to a single route get 'posts/host' => ""photos#show"""

"match 'photos/show' => 'photos#show', :via => [:get, :post]"

"you have scope logic repeated for what counts as published in your Post and User model # post.rb where(""posts.published is not null"""") #user.rb joins(:posts).where(""posts.published is not null"") Remove the duplication"

"merge the scopes (&) # user model scope :published, lambda { joins(:posts).group(""users.id"") & Post.published } # Note the use of a lambda (as Post.published will change)"

how to dynamically pass a method stored in a variable to method = :find_by_id Account.first.projects

"method = :find_by_id Account.first.projects.send method, 1"

rails -- how to disable null values in db layer

"migrations t.string :login, :null => false"

how to use a layout in an engine

"name it something other than application.html, say facebook_app.html.erb, then add layout ""facebook_app"" in the relevant controllers"

migrations datatypes - floats vs decimal

"nearly always decimals since they are far more accurate at handling fractions ""%.47f"" % (1.0/10) float: ""0.10000000000000000555111512312578270211815834045 decimal: ""0.1"""

how to use url helpers in asset pipeline

"need to access it in the long form way <%= Rails.application.routes.url_helpers.clients_url %> # best practice, I'd say, is never to do this. Instead design the javascript to take a url parameter and pass this parameter to the javascript from with a Rails view"

"what's wrong here validates_uniqueness_of :name, :scope => :user"

"needs the user_id in scope to work validates_uniqueness_of :name, :scope => :user_id"

you have this nested route resources :magazines do resources :ads end what is the named page for a new ad

"new_magazine_ad_path(@magazine) # new always in front, following by the outer resource then the inner respirce # @magazine (outer resource) necessary as a parameter since the url will be magazines/:magazine_id/ads/new"

Does @object.errors return any errors on an invalid object not yet saved?

"no # save it first, or run .valid? to generate the errors"

can you use a where clause in has_many :shown_awards to scope the association always?

"no - but you can do a conditions which is really an sql fragment has_many :shown_awards, :conditions => ""awards.award_name in (#{AWARDS.map {|a| ""'#{a}'"" }.join("","")})"" or better yet hash notation :conditions => {:award => AWARDS}"

"rails - does this run the edit action in controller render :action => ""edit"""

"no - just the view called action simplify with: render ""edit"""

"does Product.find_by_param ""something"" raise an exception if a product cannot be found matching param"

"no - only nil to raise an exception use find_by_param! (helpful in cases where you don't want the request to continue if product not found, e.g. prevent nil errors from chained methods being called on the outer resource in nested resources)"

are you limited to just one manifest file (application.css say)

"no - you can have as many as you want For example the admin.css and admin.js manifest could contain the JS and CSS files that are used for the admin section of an application and these can coexist with your application.{js,css} files"

rails - you want a form to submit a put request (it's an update form) will this work? <%= form_tag law_topic_files_path(:method => :put) do %>

"no -> the form_tag here will be ""post"" as it's the default, and the path will have the param added method?put This works instead (comma separated extra arg to the form_tag) <% form_tag(law_topic_files_path, :method => :put) do %>"

"how to get large numbers to be converted to a readable way in rails (e.g. 1.23 Thousand, 489 Billion)"

"number_to_human(1234) => ""1.23 Thousand"" # it's a helper"

rails - how to load only necessary files from asset pipeline for each controller given

"remove this from application.js //=require_tree . now either: manually add javascript files on a per view level or organise your javascripts by controller and add this line to layout <%= javascript_include_tag ""application"", controller_name %> # controller_name is a Rails core method"

"how to upgrade from current_user.authentications.create(:provider => auth['provider'], :uid => auth['uid']) to find_or_create_by"

"removed the named args syntax and just use plain old args current_user.authentications.find_or_create_by_provider_and_uid(auth['provider'], auth['uid'])"

rails -- args.extract_options! does what

"removes and returns the last element from the aray if it is a hash options(1,2, :a => :b) #=> {:a=>:b}"

"strip_links(""<a href=""http....>rails</a>"") does what"

"removes the links from the text ""rails"""

rails - change the name of a table

"rename_table :old_name, :new_name"

Rails - how to have no layout for a certain render

"render ""contract"", :layout => false"

rails - render a specific js file

"render :action => ""chooser.js.coffee.erb"""

return javascript inline from a controller

"render :js => ""window.location = #{root_path}"".html_safe"

"how to customize a collection name within a partial (rather than just defaulting to the partial name, video_listing in this case) render :partial => ""video_listing"", :collection => @recommendations"

"render :partial => ""video_listing"", :collection => @recommendations, :as => :video"

what are bind variables in rails 3 where conditions

"replace question marks with :symbols, and supply a hash of values matching symbol keys Company.where( ""id = :id AND name = :name AND division = :division AND created_at > :accounting_date"", { :id => 3, :name => ""37signals"", :division => ""First"", :accounting_date => '2005-01-01' } )"

rails - how to access the request headers backend

"request.headers[""Content-Type""]"

rails - how to get a resources :notes_files to use the named path samples_path

"resources :notes_files, :as => :samples"

rails - how to get a resources :notes_files to use the path /samples

"resources :notes_files, :path => ""/samples"""

how to restrict the routes created in rails resources [e.g. I only want the index and show]

"resources :photos, :only => [:index, :show]"

resources :photos how to have /photos/make be new and /photos/1/change be edit

"resources :photos, :path_names => { :new => 'make', :edit => 'change' } # The actual action names aren €™t changed by this option. The two paths shown would still route to the new and edit actions. Only the path names have changed."

how to have a resouce for a model Sms but with helpers with names like sms_messages_path

"resources :sms, :as => :sms_messages # The :as option overrides the automatically-generated name for the resource in nested route helpers. For example the above creates sms_messages_path"

"rails - how to customize the url of a resource from ""taxonomies"" to ""law-outlines"""

"resources :taxonomies, :path => ""law-outlines"""

how do you use respond_with in rails

"respond_to :html, :json def index respond_with(@users = User.all) end #respond_to class level marco #respond with a resource (here ActiveRecord::Base objects in an instance variable)"

"rails 3 - you want to give xml, html and json in every action of your controller. how to do this dryly"

"respond_to :xml, :html, :json def index @posts = Post.published respond_with @post end"

"shorthand for respond_to do |format| format.html format.xml end in the situation when each individual format doesn €™t receive a block and so Rails automatically tries to render the appropriate view for the mime type (e.g. action.html.erb, action.xml.erb)"

"respond_to(:html, :xml)"

rails - how to use cycle

"returns an enumerator. calling .to_s (as happens implicitly in erb) gives the return value div class=""split#{cycle(1,2,3)}"""

what does this return? Video.latest.proxy_options #latest is a scope

"returns the options set by a named_scope. p Video.latest.proxy_options # {:limit=>2, :order=>""videos.created_at DESC""}"

"rails 3.1 - what does this do? attr_accessible :title, :published_at, :as => :admin"

"roles for protecting access to attributues during mass assignment # usage: Post.new(params[:post], :as => :admin)"

"rails - what does memoize do in this case def total_budget self.available_accounts.inject(0) { |sum, a| sum += a.budget } end memoize :total_budget"

"roughly same as this def total_budget @total_budget ||= self.available_accounts.inject(0) { |sum, a| sum += a.budget } end"

rails - where do transactions automatically occur

"save & destroy (validations, callbacks)"

rails - if you want to change url defaults (e.g. /new to /make) for a whole block of resources use

"scope :path_names => { :new => ""make"" } do resources :photos end"

how to write a method which can be called on a named scope

"scope :with_habits, joins(:habits) do def activate each { |i| puts i } end end"

how to open a link in a new window

"set :target to ""_blank"" link_to ""External link"", ""http://foo.bar"", :target => ""_blank"""

what does to link_to_if do if it returns false for the expression

"shows the text, just doesn't link it up"

rails - why might it be a good idea to place the admin interface on a special subdomain such as admin.application.com and use a separate app with separate user management

"since it makes stealing an admin cookie from the usual domain, www.application.com, impossible. This is because of the same origin policy in your browser: An injected (XSS) script on www.application.com may not read the cookie for admin.application.com and vice-versa."

how to send a single pixel of data via a rails controller

"single_pixel = File.read(File.join(Rails.root, ""app"", ""assets"", ""images"", ""single_pixel.png""), :mode => ""rb"") #IRL you might cache this for added speed send_data single_pixel, :filename => 'single_pixel.png', :type => 'image/gif'"

new_seller_path OR new_sellers_path

"singular - new_seller_path # inconsistent with url, which will be sellers/new"

"what is wrong with this? User.find(:first, :conditions => ""username = '#{params[:username]}'"

"sql injection can happen as user input is placed directly into the DB query # Instead # option1) use syntax such as Model.find(id) or Model.find_by_some thing(something) # option2) manually sanitize with ? notation Model.where(""login = ? AND password = ?"", entered_user_name, entered_password) # option3) pass a hash Model.where(:login => entered_user_name, :password => entered_password)"

"alt syntax for stub_chain(:one,:two,:three)"

"subject.stub_chain(""one.two.three"").and_return(:four) subject.one.two.three.should eq(:four)"

yes / no - how to translate in rails

"surround the keys in quotes in the yaml file instead of the normal yes: ""si"" to 'yes': ""si"""

"fix this problematic file in photo_multi_upload.js.coffee.erb (asset pipeline) 'swf' : <%= asset_path 'uploadify.swf' %>,"

"swf' : ""<%= asset_path 'uploadify.swf' %>"","

rails forms -- collection select take text and db values as symbols or string

"symbols :id, :name"

Pro-tip for reducing brittleness in integration tests that access view

"test DOM, IDs or classes (then promise that at design level these won't be changed) sometimes it can be good to create non-design css identifiers just for testing"

"what's wrong with testing this in routing rspec? :post => ""/authentications/create"""

"test this instead :post => ""/authentications"""

"when choosing the order of a compound index, which column should be mentioned first"

"the column with the MOST unique values (e.g. if created_at has 600 values and language has 6, then index created_at first) add_index :conversations, [:created_at, :language_code]"

what's wrong with this member route? (resource is products) product_dashboard_path

"the member part is not in front (members and new and edit are always in front) dashboard_product_path # think of the new/edit paths as members too: # new_product_path, edit_product_path"

what is the 2nd arg of increment_counter?

"the object id number e.g. Habit.increment_counter(:successful_days_count, 72)"

what must you name a class file in order for rails 3 to find it

"the same name as the class itself e.g. a class Awarder in a file named awarding.rb won't be loaded, change to awarder.rb and you are fine"

rails - what is the easiest way to scope actions

"through a has_many relationship €¢ We can scope all :user role methods to that particular user. This allows us to access data through the current user, as opposed to using some request parameter €"such as user_id. (which could be easily spoofed)"

what to watch out for with simple sql searches (e.g. in where statements)

"to account for lower case where(""LOWER(title) LIKE ?"", ""#{letter.downcase}%"")"

Rails - what is the purpose of boot.rb

"to configure the application's load path e.g. $:.unshift File.expand_path('../../../../lib', __FILE__)"

good use case for polymorphic model (railscast on polymorphism)

"to have comments on photos, articles, pages etc. and be able to get the relevant associated model through a common interface (e.g. commentable)"

What must you remember about named paths when in emails

"to use root_url not root_path (path doesn't include the hostname, url does.. and the hostname is necessary when someone is clicking from somewhere external to your site)"

rails - when testing how a model deals with parameters what must you remember

"to write params as strings not symbols # {""id"" => ""2"" }"

rails - how to get join models in the json (e.g. a user connects with a twitter_identity and a facebook_identity table)

"to_json(:include => [:twitter_identity, :facebook_identity])"

rails - how to turn a long piece of text into a shortened extract

"truncate(""Once upon a time in a world far far away"", 14)"

"sql, rails - how does this use data on an association for ordering? joins('left join shows on shows.act_id = acts.id'). joins('left join attendances on attendances.show_id = shows.id'). order('count(attendances.id) desc'))"

"two joins are done to reach the attendances.id, then this is used to order"

how to stub this code in rspec @user = current_site.users.new

"u=stub(:user) controller.stub_chain(:current_site, :users, :new).and_return(u)"

rails - what does link_to use under the hood

"url_for(:controller => 'users', :action => 'new', :message => 'Welcome!', :only_path => true)"

how to rewrite the ActiveRecord default accessor for a length attribute to actually store data in seconds

"use ""write_attribute"" def length=(minutes) write_attribute(:length, minutes.to_i * 60) end"

named scope to get orders in the last week

"use a lambda so that the temporal element gets regenerated every time the scope is called scope :last_week, lambda { where('created_at > ?', 1.week.ago) }"

how to do a redirect in rails 3 routes

"use match match ""/products/contract-law"" => redirect(""/products/contract-law-by-oxlaw2010"")"

"how to require that a posts resource route is prefaced with ""teachers"" WITHOUT needing to change the controllers, views to accomodate a namespace"

"use scope scope ""/teachers"" do resources :posts end"

rails 3.1 - what does identity map do

"user1 = User.find(1) # => #<User id: 1, name: ""Josh""> user2 = User.find(1) # => #<User id: 1, name: ""Josh""> user1 == user2 # => true, b/c AR::Base recognizes that # they have the same primary key # without identify map user1.object_id == user2.object_id # => false # with identity map means both users will have same object_id"

"what's nice about this code? class Following belongs_to :followee, class_name: ""User"" belongs_to :follower, class_name: ""User"" class Capsule belongs_to :creator, class_name: ""User"""

"uses the same User class in many places yet with semantic closeness # remember to reflect changes with foreign_ids # has_many :capsules, foreign_key: ""creator_id"""

how to use rails try where attempted function has multiple arguments

"using comma separated args .try(:update_attribute, :name, val)"

"rails - conditionally apply a validation if a certain setting is used validate :invite_code_is_valid, :on => :create"

"validate :invite_code_is_valid, :if => Proc.new { AppConfig.config[:beta] }, :on => :create"

rails 3 - validate something is an positive non-zero integer

"validates :credits, :numericality => { :greater_than_or_equal_to => 0, :only_integer => true }"

rails - validate uniqueness of permalink within an associated subject model

"validates_uniqueness_of :permalink, :scope => :subject_id"

rails - why store an asset in vendor or lib

"vendor - someone else maintains it - e.g. jquery lib - you maintain it alone, but it's not specific to the current app"

"what was the issue here? OLD_CUSTOMERS = {:jack => 1, :john => 4} authenticate_or_request_with_http_digest do |email| OLD_CUSTOMERS[email] end"

"when rails passes the password username pairs they will be strings, but the OLD_CUSTOMER hash has symbols and integers fix by converting the keys and values to strings: OLD_CUSTOMERS = {""jack"" => ""1"", ""john"" => ""4""}"

rails - what is bootstrapping (controller/views)

"when you supply data that a javascript client will need alongside the html that also brings the javascript client example in slim javascript: homophonesJson = eval(""#{j (raw @homophones)}"");"

how does Rails protect against cross site forgery

"whenever a form or AJAX request is used in a Rails app a security token is added. This token is stored as a random string in the session, to which an attacker does not have access. When a request reaches your application, Rails verifies the received token with the token in the session. If this token doesn't match what Rails expects then the action won't be carried out."

rails - select all from the database in certain date range

"where(""created_at between ? and ?"", ""2011-11-12"", ""2011-11-13"") # note the date format YYYY-MM-DD"

"rails - where email is not ""[email protected]"" or ""[email protected]"""

"where(""email != ? AND email != ?"", ""[email protected]"", ""[email protected]"") #note the need to write out the email != expression again twice"

between query for getting results in one day scope (e.g. the day results within the scope of today)

"where('day_results.created_at between ? and ?', Time.new.at_beginning_of_day, Time.new.end_of_day)"

two OR conditions in a where clause

"where('workshops.user_id = ? OR workshop_applications.user_id = ?', user.id, user.id)"

"what's wrong with this: link_to ""GrindsWorld"", ""www.theirsite.com"""

"will link to a www.mysite.ie/www.theirsite.com add http:// to link to external sites link_to ""Their site"", ""http://www.theirsite.com"""

rails - how to include the same association methods on different associations

"write the methods inside a module, say RenamingMethods has_many :posts, :extend => RenamingMethods"

"rails - does accepts_nested_attributes_for allow you to update an existing nested record class Member < ActiveRecord::Base has_one :avatar accepts_nested_attributes_for :avatar end member exists, and it has an avatar with id=2, icon=""happy"""

"yep # params = { :member => { :avatar_attributes => { :id => '2', :icon => 'sad' } } } # member.update_attributes params[:member] # member.avatar.icon # => 'sad'"

"is passing an array like so legal in ActiveRecord NotesFile.where(:subject_id => [117,118])"

"yes - executes a subject_id IN (117,118) getting all the values"

"rails - does order of Gems in Gemfile matter? gem ""capistrano-deepmodules"" gem ""capistrano"""

"yes -- sometimes problem with hipstery -- capistrano deepmodules expected capistrano gems to be available gem ""capistrano"" gem ""capistrano-deepmodules"""

rails - can dynamic attribute based finders be called on scopes?

"yes Payment.order(""created_on"").find_all_by_amount(50)"

"rails -- you want a jQuery get request to render the js view. what's wrong? $.get(""/events"")"

"you need ""/events.js"" otherwise there is ambiguity about the format to be returned"

What does rails call on @post to turn post_path(@post) into a url

.to_param

"what value does the final expression here return project_1.milestones.length # - Hits the db's Milestones table. and CACHES Milestone.create(:project_id => 1, :name => 'New Milestone') project_1.milestones.length"

0 -- the milestones (not 1 like you expect) since project_1.milestones was cached use this instead of override the caching: project_2.milestones << Milestone.create(:name => 'Another Milestone')

how to convert a string to a date in rails

06/15/2008'.to_date takes multiple formats

if changing the name of an ActiveRecord model what else needs to be changed

1 database table name (or at least you should configure the renamed model to use the old table name) 2 all references to Model model @model and so on in the project 3 all relevant file names

According to Gary Bernhardt what three things should a controller do:

1) Delegate to SomeClass 2) Choose which SomeClass to delegate to based on higher-level state: is the user logged in? 3)Choose where to send the user (to a template or to a redirect) based on what SomeClass did when we delegated to it.

when you absolutely must verify someone is human what should you use

1) a captcha plugin / gem # increasingly this isn't true due to captcha farms... 2) phone number verification

"If you have a routing namespace block (say Law), what 3 things must you do for the contained resources to work in the app"

1) namespace controllers with module Law 2) move views and controllers into a law folder 3) change urls in links (don't forget forms) to law_old_path

security - how might someone get another user's cookie in an internet cafe

1) sniffing on the wireless. prevent by using ssl to encrypt your communications 2) someone forgetting to log out- make your log out button big and time out sessions short

rails - to render js inline from a controller you must

1) use .html_safe on the js 2) use a :remote => true on the button or link (else you are redirected to a new page)

when to use observers

1) where a subsystem is used by multiple classes 2) when you foresee the need to turn off certain systems in certain environments (e.g. turn off emailers in development) e.g. class Applicant after_create :send_thanks def send_thanks Email.deliver_thanks(self) end becomes: class NotificationObserver observe Applicant def after_create(project) Email.deliver end end

"how to get bytes represented in mb, gb etc. in rails"

number_to_human_size(1234567) => 1.2 mb

rails - how to convert numbers to percentages

number_to_percentage helper number_to_percentage(28) => 28%

order has many products... how to get just the unique ones

order.products.uniq #uniq is an ActiveRecord method here

XMLHttpRequest's in rails render what filetype by default (e.g. if the action hit was pages#create)

pages/create.js

assert an access denied with rspec

response.code.should == '403'

how to check for correct redirection in rspec controller tests

response.should redirect_to(my_path)

explan what Rails new_record? does

returns true if object hasn't been saved yet

how to set an AR objects attributes w/o saving

@model.attributes = {}

longer way for this to get past no method error @person.try(:name)

@person && @person.name

rails modification of Object#send which does not raise a NoMethodError exception if the receiving object is a nil object

@person.try(:name)

rails what is wrong with this logic -if @post.subjects #ActiveRecord association

@post.subjects is never false.... there will always be at least be an empty array which evals to true should be - unless @post.subjects.empty?

in a has_and_belongs_to_many relationship how to build a new object off an existing one

@post.subjects.build

get an array of attribute names for an ActiveRecord::Base instance

@product.attribute_names

get a hash of attributes with values for an ActiveRecord::Base instance

@product.attributes

Rails - check if a record has any unsaved differences

@product.changed?

how to get an array of error message texts on the @subject model

@subject.errors.full_messages

user has_one seller create a seller from @user

@user.create_seller(attrs)

"what's wrong with this code? # User model has_one :car # controller def index @users = User.paginate( :page => params[:page], :per_page => 20 ) end # view <% @users.each do |user| %> <%= user.car.name %> <% end %>"

@users.each {... something with car...} causes N+1 queries for each car object as the cars needs to be fetched from the database separately (20 times for per page here) # fix by including the car objects in the ActiveRecord query # Controller # @users = User.includes(:cars).paginage...

rails - two ways to disable email being sent in development mode

action_mailer.perform_deliveries = false

When you modify a Gemfile what must you do for an app to see thse changes

run bundler and restart the app

rails - reject blanks in accepts nested attributes

:reject_if => :all_blank

rails - consequence of transactional nature of ActiveRecord saving

:after_save callbacks (etc.) don't have access to updated record at database level (e.g. rebuilding search) use after_commit callback for this

rails - how to get truncate set to 40

:length => 40

you have an observer class ResultObserver what does it need to inherit from?

ActiveRecord::Observer

what exception is thrown if ActiveRecord can't find the record with the params passed

ActiveRecord::RecordNotFound

How many model methods should each controller action call?

As few as possible. Ideally one.

Why should you always explicitly assign variables when using partials (instead of relying on the instance variable such as @post)

Because sometimes the partial is used across multiple view templates - and the instance_variables available to the partials might have different names across each of these views. by using an explicitly assigned variable you can adapt the instance_variable into a standarized local variable used withn the partial

why was this test failing unsuccessful_result = Factory(:result) subject.results << unsuccessful_result subject.remove_last_added_result subject.results.should_not include unsuccessful_result **DEBUGGING HELL**

Because subject#results was cached (to include the unsuccessful_result) and didn't represent the actual state of the database once we called remove_last_added_result # fix it like so: modify the assertion in the last line to be subject.results.reload.should_not include unsuccessful_result

When should you write tests?

Before code. This gives you the advantage of writing code that is easier to test... which in turn gives you less coupled tests.

how to benchmark something in rails console

Benchmark.measure { code }

polymorphic_url does what

Constructs a call to a named RESTful route for the given record and returns the resulting URL string. e.g. polymorphic_url(Comment) is comments_path polymorphic_url(comment) is comment_path(comment)

"You have an Error model with ""name"" column in db. How to get all names present in db efficiently?"

Error.select('DISTINCT name')

class_inheritable_accessor RAILS ONLY - can changes descendants make to this attribute (inside themselves) have an effect on the original parent class?

NO - because it give descendant classes a COPY of it's parents attributes instead of a pointer to the same (like cattr_accessor would)

rails - load seed data from an engine (using code)

FacebookApp::Engine.load_seed

What does benchmarking mode do when used in performance testing?

Finds out how fast each test runs.

how to destroy all the Habits from today (using named scopes)

Habit.today.destroy_all

rails - get a model without default scope

Model.unscoped

rails -- convert a time object to a date object

Time#to_date

rails -- how to get time at start of day

Time.new.at_beginning_of_day

How to cleanly limit access to resources to certain users in rails

Use an association then scope by the current_user.resources e.g. Look at this show action @event = current_user.events.find(params[:id])

rails - when is ActiveRecord.joins a better option than ActiveRecord.includes

Use joins whenever you don't need to instantiate the models from the joining table (e.g. the other table is only required to check for a condition that's used to select which objects you'll need) Use includes whenever you need to instantiate the models from the joining table (e.g. iterating through a post's comments in your views)

how to do add erb to a css files .class { background-image: url(<%= asset_path 'image.png' %>) }

add .erb to the css file (e.g. application.css.erb)

"besides a foreign key, what else will you need on the polymorphic database model"

a type column e.g. a polymorphic comment will have a commentable_type string column as well as a commentable_id column

rails - you want to require net/http... where

application.rb

how to package up code in a template to run at the end of an app generation

array = [] array << lambda do code end array.each {|l| l.call }

"how to convert an array [1,2,3] to a string ""1, 2 and 3"" in rails"

array.to_sentence

why would you pass a rack application variable to another rack application?

as middleware filters -- i.e. to stop certain ip addresses

before going out of your way to write a named scope...

ask if rails built in finders can do the job

with asset pipeline what differs in development mode?

assets.debug config is true - which means the files are not concatenated

why can't you use x_path urls in email templates

because email clients won't have a concept of relative url and so path makes no sense instead use x_url

"why would you say Article.order(""name"") lazy loads"

because it just returns an ActiveRecord::Relation object query not performed till you enumerate

rails - why is this code so dangerous when using ActiveRecord to have a user with many habits current_user.habits.reject! {|h| h.successful_completion_ratio <= 0.75 }

because it redefines the habits array before it is used in all other calculations on that page

"in ruby, why might models used in similar ways (or interchangeably) not need to inherit from a common base class."

because ruby is dynamically typed -- only have to respond to same methods

Rails - why should you not put secret information inside cookie based sessions (these being the standard session types in Rails)

because the contents can be read by users (not encrypted)

"validates_inclusion_of :name, :in => POSSIBLE_AWARD_NAMES POSSIBLE_AWARD_NAMES = [1,2,3] why does this return an error"

because the validator references a constant not yet defined. put validator below constant declarations

why is it better to instantiate association variables (e.g. @notes_files = @product.notes_files) in the controller instead of in the view

because you can see what objects are going to be necessary at a glance (and can think about optimising queries with includes and so on)

"=render :partial => ""footer_contact""Â Â why might this give ActionView::MissingTemplate error"

because you enter a different controller and it can no longer find partial -- either use absolute path to partial or put it in layouts if global

rails - are gems loaded before or after your rails app

before # thus your own config values will overwrite configurations in the gem

solve ActionView::Template::Error (application.css isn't precompiled):

bundle exec rake assets:precompile

rails - how do you get HTML method verification for free

by declaring resourceful routes # resources :products

rails - asset pipeline gotcha for js heavy files

by default it will load all files in assets dir. customize either by removing the require_tree and requiring what's needed on a per view basis or by placing heavy ones in lib/vendor and loading as required

how to scope a delete action so the current user can only delete models he is associated with

call the find from the scope association current_user.grind.subjects.find(params[:id])

rails - what will cause a stack overflow in ActiveRecord callbacks

calling something like save in a before_create

"rails 3.2 - what does this do: config.railties_order = [Blog::Engine, :main_app, :all]"

changes load order of Railties

engine yard article paradigm for speeding up rails apps

do database work in the database - e.g. instead of iterating through objects in ruby do it in your database since it's optimised for lots of things Article.comments.count(:conditions => {} )

what's wrong with this Rails.development?

doesn't work Rails.env.development? instead

does rake db:test:purge drop the tables or just delete data

drops tables - sometimes too much # rake db:test:load Recreate the test database from the current schema.rb -- probably useful after running purge

"auto_link not only turns web addresses into links, but also ..."

email addresses

how to test rake tasks

encapsulate the task into a class/method and test that class/method

what does :bulk => true do in migrations

ensure that all schema changes happen in a single ALTER statement

"rails 3.2 - what does the namespace do? <%= form_for(@offer, :namespace => 'admin') do"

ensures uniqueness of id attributes on form elements. The namespace attribute will be prefixed with underscore on the generated HTML id

rails - ActiveRecord::Base#find() surprisingly returns what if nothing found

error - like the find_by_attr! methods

"CGI.escape_skipping_slashes """" (RAILS)"

escapes any non letter or non number in a string being used for a URL

how to access the connection between two models without going through all the intermediaries

execute a fresh sql query in a method using more cheaply accessible foreign_ids class User def assignments Assignment.where(:workshop_id => workshop_ids) end

what does this line do: config.to_prepare do MyRailtie.setup! end

executes something once in production and before each request in development

rails - mistake when using slim/haml divs and you can't seem to grab a certain element

failing to indent contents correctly into the containing div in the slim/haml

what does @object.save return if validations fails

false (but no exception)

if you want number_to_currency to give you cents what do you do

feed it a float (i.e. a number with a decimal to start with) number_to_currency(12.34)

whats the difference between Model.find and Model.find_by_id

find_by_id returns nil if nothing returned find raises an exception if nothing returned

rails - opposite (order) of find_by

find_last_by

whenever you modify a migration file (without creating a new one) what is a massive mistake

forgetting to also modify the down

"shorter syntax for match 'products', :via => :get"

get 'products'

ar base instant method to increment a column

h.increment(:successful_days_count) DOESN'T SAVE

are has_many finders instance or class methods

instance methods (i/e they must be called on instance objects)

error 500 means

internal server error

"longer_than = lambda {|len, str| str.length > len } how to make a new proc which takes one argument and compares this with the length of 5"

longer_than_5 = longer_than.curry[5]

if your test database is keeping objects how do you fix this

make sure your rspec spec helper is using transaction fixtures: config.use_transactional_fixtures = true clear out the database: rake db:test:purge

"shortcut for: match 'products/recent', :to => 'products#recent'"

match 'products/recent'

"what does the allow_nil option do here: delegate :zoo, :to => :bar, :allow_nil => true"

means that an exception will not be raised if zoo is called and there is no bar item associated

"you are rendering a collection of partials as = render :partial => ""micro_profile"", :collection => @profiles what variable has a reference to each profile object INSIDE the partial"

micro_profile # .... why? since the value of the partial key is also used as the variable name

what stupid mistake can you make with params and session

mixing them up - they both have similar syntax so if you are having issues double check you are not using one interchangeably for another

what is the naming convention for test filenames

model_test.rb model_spec.rb e.g. grind_test.rb

example of a railtie in a gem which changes default mailer generator to merb

module Handlers class Railtie < Rails::Railtie config.app_generators.mailer :template_engine => :merb end end

rails - how to namespace regular (non-resource) get requests

namespace :facebook_oauth do get :ask get :callback end

when building an engine facebook_app how do parameters passed via forms change (originally the param in question was email)

namespaced with the engine name - from email to facebook_app_email

user has_one :seller user.seller = other_seller if user.save necessary next to commit the changes?

no - just calling user.seller= is enough (as keys are updated in db)

rails - you want a jQuery get request to return an index.js.coffee view with erb inside. Should you append .erb to the view name?

no - just insert <%= %> anyway. # i've found that bugs arise by adding .erb in this situation

does require_tree . load assets from engines?

no - loads all css/js from the current folder (i.e. the main application's assets folder) but doesn't say anything about any engine's assets.

If you instantiate an object (without saving it - e.g. Post.new) will you see it under Post.last

no - not until it's saved

do you need to add .js here //= require jquery

no - sprockets assumes you are requiring a .js files since the filename you are calling this from will be application.js

if you use coffeescript should you modify js files directly

no - these are autogenerated from your coffee files so any changes you make directly to the JS will get overrideen

a user hm habits will this work? u.habits =nil

no -- must be an empty array at least

"can a compound index with [item_id, item_type, item_pos] be used as an index for item_type query?"

no -- since this query doesn't have item_id as it's first step

can you do this in rails? module Addressable has_one :address end include Addressable

no -- you have to do something like this instead: module Addressable def self.included(klazz) # klazz is that class object that will eventually include this module klazz.class_eval do has_one :address end end end

rails - you've build a ProductSweeper with after_save callbacks etc. is this enough

no -- you must also add this line to the relevant controllers cache_sweeper :product_sweeper

Rails - will this work Seller.count(:email => email)

no -- you need :conditions Seller.count(:conditions => {:email => email})

rails 3.1 - is this a comment in assets/javascripts/applciation.js //= require jquery

no it's part of the manifest file. it causes Rails to look in assets load path (Rails.application.config.assets) for jquery.js

what does the precision option do in number helpers

number of decimal points -- precision => 3 means .000

how to convert a number into a currency string in rails

number_to_currency(1234) $1234.00

what will go wrong with this code? def self.last_with_same_name_from_that_ip(params) if params[:subject][:name] ....

params[:subject] whatsoever might be nil leading to an error when you call nil[:name] try this instead if params[:subect] && params[:subject][:name]

rails Dispatcher does what?

passes the request to the proper controller

rails 3.1 scss should be defined on a ... basis

per model basis with separate files in assets/stylesheets/

person.name = 'Bill' .. how to check if the name attribute has changed

person.name_changed?

rails - get the lowest possible value for one column

purchases.minimum(:price)

how to add a favicon to your Rails 3.1+ app

put a favicon.ico file into the public/ directory (not into assets/images)

rails - add a new console method (top level)

put it in config/initializers # but really top level is dangerous since it will be inherited by all objects # better to namespace them e.g. def C.my_console_method

how to get rid of a plugin in rails

r plugin remove rails_upgrade

how to run a rack file

rackup filename.ru -p 3000 # - p take s the port number

rails 3 - how to get into the test enviromnet with the Rails console

rails c test

rails - how to open test console

rails console test # inconsistent with server commands - rails server -e test

rails - list the generators currently available for a particular project

rails g --help

Rails - generate a nested controller

rails g controller admin/foo bar

rails - new app in current folder

rails new . (uses current folder name)

how to start rails server in test env

rails s -e test

how to start a rails server on an alternative port

rails s -p 3001

rails - how to raise a 404 in your controller

raise ActionController::RoutingError.new('Not Found')

"what does the second param here do serialize :authorization_confirmation, AuthorizationConfirmation"

raise an exception if the authorization_confirmation is not an instance of AuthorizationConfirmation

rails 3.2 - added a validation with :strict => true What does it do?

raises an exception on validation failure

rails 3.2 run migrations only from Blog engine

rake db:migrate SCOPE=blog #also allows reverting

roll back 6 migrations in rails

rake db:rollback STEP=6

how to quickly (compared to rake:db:migrate) get the db into shape

rake db:schema:load

How to copy the structure of the development database to your testing database

rake db:test:clone

rails - recreate the test database from the schema.rb file

rake db:test:load # rake db:test:prepare is useful to run pending migrations

how to see how far a migration has gone in rails app

rake db:version # returns the timestamp of the latest migration

How to view a list of FIXME and TODO comments in your Rails app?

rake notes

rails - how to clear cookie data from a live app

rake tmp:clear

"If ActiveRecord select method is used, all the returning objects will be"

read only (by default)

you have a named scope red_items how to check if you have any matches in db

red_items.exists? #=> true

you have a named scope red_items in db how to updated all to have color black

red_items.update_all :colour => 'black'

Rails - what will NotesPack.group(:email).all do if two items have the same email address

remove them from the returned list - thus the num of items will be smaller than the count of records with email addresses

rails 3.1 - what does this do //= require_tree .

requires every file of the same type as the filename itself (e.g. js files if the above code appeared in application.js) from the current folder and its sub-directories

Rails - get rid of entire sessions

reset_session

what does this do: JobLevel.reset_column_information

resets cached info about columns (such as attr names) useful in migrations before preloading data

what typo in routes can give you a lot of trouble

resource vs resources

"when you add a ""member"" route to a resource what will the url typically be like?"

resource/id/member_route

with performance tests you determine...

where you app's memory or speed problems are coming from

rails 3 -- where clause to search for :successful being false

where(:successful =>false)

What does attr_accessible do?

whitelists the attributes that will be allowed to be set via mass assignment

rails - gotcha with update_attributes on non attr_protected attributes

will return true if you try and update a protected attribute (but will not update that attribute)

"rails - alternative syntax to write the part in bold scope :custom_finder, with_orders & Order.complete"

with_orders.merge(Order.complete)

"rails - will this create action redirect? def create @user = User.new(params[:user]) flash[:notice] = ""User was successfully created"" if @user.save respond_with @user end"

yes - it goes to the @user show page using respond_with

when creating a new object in rails (result.new) can you customize the created_at date to be another point than now

yes -- Result.new(:created_at => 1.day.ago)

Can you call ActiveRecord.includes on custom associations (i.e. ones which have conditions attached such as approved_comments instead of comments)

yes Post.includes(:approved_comments)

"does chaining of where clauses work Lead.where(""phone is null"").where(""website = 'example.com'"")"

yes it does

does this raise an error if nothing found NotesFile.find(1)

yes it does (ActiveRecord::RecordNotFound)

rails -- does this avoid the creation of the html body if etag matches request def show @product = whatever fresh_when etag: @product end

yes it does -- thus server resources are saved

"rails - does memoize method account for different inputs to a method def total_spent(start_date, end_date) self.available_accounts.where('created_at >= ? and created_at <= ?', start_date, end_date).inject(0) { |sum, a| sum += a.spent } end memoize :total_spent"

yes it tracks differing inputs automatically (handy!!!)

can the params hash be accessed in rspec

yes params[:message].should be_nil etc. works fine

Is it important to test helpers?

yes... as the app scales these can get complex.

what can go wrong with a deploy in rails 3.1 (after precompiling)

you have an image_path for an image which doesn't exist. not found be precompilation

rails - validates_acceptance_of will not work if

you haven't those attributes accessible (e.g. the :terms)

rails - if bundle is installing into a random folder (e.g. spork) what is wrong

you ran bundle install spork (setting the install dir to 'spork'... permanently) fix in .bundle/config

Why is this not ideal: Rails.logger.debug { @order }

you'll just see #<Order:0x592b8c8> # instead: Rails.logger.debug { p @order }

rails - what is shown in params if a check_box_tag isn't checked

you'll see nothing - as if the check_box never existed


Ensembles d'études connexes

British Rule in India & Independent States in South & Southeast Asia

View Set

Chapter 8 Gestalt Therapy Practice Questions

View Set

AP Chemistry: Unit 3 College Board Questions

View Set

Tempkin: Thyroid and Parathyroid

View Set

History of Graphic Design Chapters 19-21 Test Review

View Set

Florida Statues, Rules, and Regulations

View Set

Sorry, no manipulations with clipboard allowed

View Set