ubuntu, ror, jQuery, css, website memo
太嫩, 沒啥心得, 用來紀錄每天學的
2009年3月20日 星期五
nested include
嵌套使用rails find :include選項
nested include in rails
弄幾個 example 就懂啦
class InventoryLine
belongs_to :item
belongs_to :swap
end
class Swap
belongs_to :person
belongs_to :source, :class_name => “Person”, :foreign_key => :source_id
belongs_to :destination, :class_name => “Person”, :foreign_key => :destination_id
end
class Person
has_many :swaps
has_many :swaps_as_source, :class_name => “Swap”, :foreign_key => :source_id
has_many :swaps_as_destination, :class_name => “Swap”, :foreign_key => :destination_id
end
#{:first_table => :second_table}
@inventory_lines = InventoryLine.find(:all, :include => [{:swap => [:source, :destination]}, :item])
#如果你只有include 一個association 的話, 沒問題
Person.find(:all, :include => :swaps_as_source, :conditions => "swaps.destination_id IS NOT NULL")
#如果你include 了兩個 association 卻又是對應到相同的table 就要小心了, 第一個include 的仍然是用table name, 但是後面的就是本身的複數的 association 加上parent table name
Person.find(:all,
:include => [:swaps_as_source, :swaps_as_destination],
:conditions =>
"swaps.destination_id IS NOT NULL AND
swaps_as_destinations_people.source_id IS NOT NULL"
#因為是在people table 做search
#swaps_as_destination 複數 加上 people
)
沒有留言:
張貼留言
較新的文章
較舊的文章
首頁
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言