การใช้ find + include ในกรณีที่มี condition ทั้งสอง model

  • warning: realpath() [function.realpath]: SAFE MODE Restriction in effect. The script whose uid is 1005 is not allowed to access /tmp owned by uid 0 in /var/www/sites/sugree/codenone.com/subdomains/www/html/includes/file.inc on line 190.
  • warning: realpath() [function.realpath]: SAFE MODE Restriction in effect. The script whose uid is 1005 is not allowed to access /tmp owned by uid 0 in /var/www/sites/sugree/codenone.com/subdomains/www/html/includes/file.inc on line 190.

ในกรณีที่ผมมี 2 model ลักษณะนี้

class Book < ActiveRecord::Base
     has_many :comments
end
 
class Comment < ActiveRecord::Base
     belong_to :book
end

ถ้าผมต้องการดึง Book พร้อม Comment โดยจะดึงเฉพาะ Book ที่อยู่ในกลุ่ม "ruby"

books = Book.find(:all, :condition => {:group => "ruby"}, :include => [:comments])

แต่ถ้าผมต้องการดึงมาเป็น array ของ comment แต่ใช้เงื่อนไขเดิมว่า Book ของ comment นั้นจะต้องอยู่ในกลุ่ม "ruby"

comments = Comment.find(:all, 
                        :include =>[:book], 
                        :condition => ["books.group = ?", "ruby"])

ในกรณีนี้ถ้าผมมี condition สำหรับทั้ง comment และ book ก็ทำได้ทันที

comments = Comment.find(:all, 
                        :include =>[:book], 
                        :condition => ["books.group = ? and 
                                        owner = ?", "ruby", "Ramda"])

คำถามไม่มีครับ :P ระหว่างที่เขียนมาถามบังเอิญหาวิธีได้เลยตอบตัวเองไปเลย

จะมีติดใจตรงที่อยากใช้ condition เป็นแบบนี้

:condition => {:book.group => "ruby", :owner => "Ramda"}

แต่มันทำไม่ได้ :'(

ขอบคุณครับ อ่านแล้วสนุกมาก

ย้าย Codenone

ประกาศย้าย Codenone ไปใช้ Forum ของ Blognone แทนครับ ตามไปตั้งกระทู้ต่อได้ที่ Codenone Forum (รายละเอียดอ่านจากกระทู้ ย้าย Codenone ไปรวมกับ Blognone)

กระทู้เก่าๆ จะย้ายตามไปในภายหลัง ตอนนี้ปิดการโพสต์กระทู้ไว้ เหลือไว้เฉพาะอ้างอิงเท่านั้น