Monday, February 4, 2008

Andrzej's Rails tips #1

has_many :through, :uniq=>true

It's quite common that when you need to use has_many :through, you actually want to see unique objects. Today, I had a need to display a list of producers based on an order.

In my design I have:

Order.has_many :line_items
LineItem.belongs_to :producer
Order.has_many :producers,
:through => :line_items

With this in place, if an order has two products, each of them belonging to the same producer, then order.producers lists the same producer twice.
Adding :uniq => true solves the problem:

Order.has_many :producers,
:through => :line_items,
:uniq => true

More information about it on John Susser's blog.

RESTful routes and pdf

If you have an action that responds to many formats (html, rss, pdf), you can still use a RESTful route with a 'formatted' prefix:

link_to "PDF format",
formatted_order_path(@order, :pdf)

Found on Railscast #78.

No comments: