Showing posts with label gotcha. Show all posts
Showing posts with label gotcha. Show all posts

Sunday, February 28, 2010

Rails, RedCloth, textilize gotcha


# This doesn't work! It returns html in pure strings and not the html elements!

textilize @blog.content

# Need this extra step.

sanitize(textilize @blog.content)


**UPDATED**

The problem lies that Rails 3 ERB uses h() helper by default

<\%= xxx %>
<\%= h(xxx) %>
To get past this use context_tag() or raw()

xxx = content_tag(:p, "blah")
<\%= xxx %>

xxx = "<\p>blah<\/p>"
<\%= raw xxx %>

Wednesday, February 10, 2010

Factory Girl has many associations gotcha

Suppose Post has many Items

class Post < ActiveRecord::Base
has_many :items
end

class Item < ActiveRecord::Base
belongs_to :post
end

When setting up data for tests using factory girl

Factory.define :item do
u.post {|p| p.association(:post)}
end

Don't do this!

@post.items << Factory(:item)

Factory will create an item with another post_id and this will not be automatically changed to @post.id. Instead do this.

Factory(:item, :post => @post)

Tuesday, August 4, 2009

Avoid multi-level associations using named scope

I had the a "local_address" method in Enrollment which looks for first local address

class Enrollment < ActiveRecord::Base

has_many :addresses

def local_address
addresses.local.last
end

end

class Address < ActiveRecord::Base

belongs_to :enrollment
belongs_to :address_type

named_scope :local, {
:joins => "LEFT OUTER JOIN address_types ON address_types.id = addresses.address_type_id",
:conditions => "address_types.name = 'Local'"
}

end


Calling the "@enrollment.local_address" then leads to very unoptimized queries. To optimized it I had to call "Address.find" directly from the "local_address" method.

def local_address
- addresses.local.last
+ Address.last :include => :address_type, :conditions => ["address_types.name = 'Local' and enrollment_id = ?", id]
end