Showing posts with label rails. Show all posts
Showing posts with label rails. Show all posts

Thursday, October 25, 2012

Update all associations of a Rails model


  @msg_thread.messages.update_all(status: 'read')

Tuesday, October 16, 2012

Rails scaffold only the controller resource


rails g scaffold_controller users

Thursday, August 16, 2012

Share methods between controller and views in Rails

The key is to put methods into ApplicationHelper and call them in the controller

module ApplicationHelper
  def user_unauthorized?
    ...
  end
end

class HomeController < ApplicationController
  def index
    redirect_to '/foo' if view_context.user_unauthorized?
  end
end

Sunday, March 6, 2011

Delegate getting name attribute of associations


# Instead of 

def guest_name
  guest.try(:name)
end

# Use delegate

delegate :name, :to => :guest, :allow_nil => true

Wednesday, January 12, 2011

Difference between includes and joins in rails

Jason please repeat after me ten times.

includes does "LEFT OUTER JOIN" while joins does "INNER JOIN"

Monday, January 10, 2011

Overide default scope in Rails


# Our default scope in question
class Product < ActiveRecord::Base
  default_scope order('created_at desc')
end

# This won't work
Product.order('created_at asc').all

# Method 1: unscoping
Product.unscoped.order('created_at asc').all

# Method 2: with_exclusive_scope
Product.with_exclusive_scope{ Product.order('created_at asc').all }

references: http://ryandaigle.com/articles/2008/11/18/what-s-new-in-edge-rails-default-scoping

Wednesday, December 1, 2010

Finding source location for a rail method


# Eg. if you want to find source location for DateTime.tomorrow

irb(main):001:0> DateTime.method(:tomorrow).source_location

Monday, September 13, 2010

Sorting searchlogic results


params[:filter][:order] = "ascend_by_created_at"
@search = Note.search(params[:filter])
@notes = @search.all

Functional test for respond_to :json in Rails


# Notes controller

def index
...
  respond_to do |format|
    format.json { render :json => @notes }
  end
end

# Notes functional test

params = {:format => 'json', :title => ...}

get :index, params

notes = JSON.parse(@response.body)
assert_equal note.title, notes[0]['note']['title']

Tuesday, July 20, 2010

Using curl to post data to a rails app


curl -X POST -d "location[lat]=111&location[lng]=222" http://localhost:3000/users/123/devices/456/locations

However rails require authenticity token. To overcome that just turn forgery protection off.

# config/environment.rb
config.action_controller.allow_forgery_protection = false

Tuesday, May 4, 2010

Finding uninvoiced fees in rails


# Models

Class InvoiceItem < ActiveRecord::Base
  belongs_to :fee
end

Class Fee < ActiveRecord::Base
  has_one :invoice_item
end

# Namedcope in Fee model

namedscope :uninvoiced, {
  :conditions => "fees.id NOT IN (SELECT fee_id FROM invoice_items)"
}

Tuesday, November 17, 2009

Authlogic login in rails functional tests


# Place this at the top of test/test_helper.rb
require "authlogic/test_case"

# Activating authlogic in before each test
def setup
activate_authlogic
UserSession.create(Factory(:teacher))
end

Wednesday, October 28, 2009

String value not displayed in input text field in a form

If you have the following,

<% form_tag '/index' do %>
<% text_field_tag 'date', '2009-01-01' %>
<% submit_tag 'Go' %>
<% end %>

You would think the textfield above would have "2009-01-01" string displayed. But it is not so. Need to specify "GET" method.

<% form_tag '/index', :method => :get do %>
...

Sunday, October 25, 2009

Format string for titles

How to change "ClassTest" to "Class Tests"?

"ClassTest".titlecase.pluralize

or

"ClassTest".titleize.pluralize

Specify form method when generating url route for edit form

Scratch head moment when I didn't specify ":method => :put" for edit form coz the form keeps leading me to "create" action.

<% form_for @class_test, :url => class_test_path(@class_test) do |f| -%>
<%= render :partial => f %>
<%= f.submit "Save" %>
<% end -%>

This was resolved after specifying the "put" method.

<% form_for @class_test, :url => class_test_path(@class_test), :html => {:method => :put} do |f| -%>
<%= render :partial => f %>
<%= f.submit "Save" %>
<% end -%>

Monday, October 19, 2009

Error using validation hooks with before_save callback


# This will throw "Schedule can't be blank" error as any changes made in before_save callback somehow gets lost
class Assessment < ActiveRecord
validates_presence_of :schedule

attr_accessor :date, :time
before_save :set_schedule_from_date_and_time

private

def set_schedule_from_date_and_time
if self.date && self.time
self.schedule = Time.parse("#{date} #{time}")
end
end

# The trick is to use before_validation
before_validation :set_schedule_from_date_and_time

Tuesday, October 6, 2009

Be careful with button_to in RESTful routes


# This will be default use POST method which in this context be sent as a create resource
<% form_for @course do |f| %>
...
<% end %>
<%= button_to 'Cancel', courses_path %>

# Specify GET method explicitly so it will call index resource instead
<%= button_to 'Cancel', courses_path, :method => :get %>

Monday, September 28, 2009

Problem with nested attributes for has one relation in form view

Scenario:

# app/models/teacher.rb
has_one :profile
accepts_nested_attributes_for :profile

# app/controllers/teachers_controller.rb
def new
@teacher = Teacher.new
@teacher.profile = Profile.new
end

If the following view give you error.

# app/views/teachers/_form.html.erb
<% form.fields_for :profile do |profile_form| %>
...
<% end %>

# Error in console
You have a nil object when you didn't expect it!
You might have expected an instance of ActiveRecord::Base.
The error occurred while evaluating nil.new_record? (ActionView::TemplateError)
On line #1 of app/views/teachers/_form.erb

1: <% form.fields_for :profile do |profile_form| %>

Then it means you don't have any fields for parent object

<%= form.text_field :login %>
<% form.fields_for :profile do |profile_form| %>
...
<% end %>

Tuesday, September 1, 2009

Do not use Ruby's Enumerable find() method in Rails

According to ruby doc.


find enumObj.find {| obj | block } -> anObject or nil

Synonym for Enumerable#detect .


However if you ever try to use Enumerable#find in Rails, you'll get a "cannot find object without object id" error.

Better to use Enumerable#detect

The problem with using Rail's try() method


@jasonong Try not to use Rail's try() method; makes debugging
difficult coz error not thrown.