join - Multiple queries are executed during fetch of an associated class - ruby on rails -
i want optimize code performance in such way instead of multiple queries; in single query can information database.
my code this:
i have class (called class:a) have sti (let type a1 , type a2).
and 2 more class(let class b , class c) associated class a.
something this...
class < activerecord::base has_many :b has_many :c blahblah end class b < activerecord::base belongs_to :a blahblah end class c < activerecord::base belongs_to :a blahblah end class a1 < blahblah end class a2 < blahblah end
now, when trying load a1 total 9 times queries executed... can optimize in a single query??
i trying excute this:
@datas = a1.where("id" < 5 )
console output:
a1 columns (1.0ms) show fields `a` a1 load (2.2ms) select * `a` (id < 5) , ( (`promotions`.`type` = 'a1' ) ) c load (0.4ms) select * `c` (`c`.a_id = 1) c columns (0.7ms) show fields `c` sql (0.1ms) set names 'utf8' sql (0.1ms) set sql_auto_is_null=0 b load (0.4ms) select * `b` (`b`.a_id = 1) b columns (0.7ms) show fields `b` rendered blahblah (42.1ms) c load (3.5ms) select * `c` (`c`.a_id = 2) b load (5.3ms) select * `b` (`b`.a_id = 2) rendered blahblah (13.1ms) c load (3.5ms) select * `c` (`c`.a_id = 3) b load (5.3ms) select * `b` (`b`.a_id = 3) rendered blahblah (13.1ms) c load (3.5ms) select * `c` (`c`.a_id = 4) b load (5.3ms) select * `b` (`b`.a_id = 4) rendered blahblah (13.1ms)
can information 3 tables in single query?
my try
@datas = a.join(:b).join(:c).where("id" < 5)
but got same... multiple queries executed instead of single query....
can me in this????
thanks in advance.
edit
second try: @datas= a.find(:all, :joins=>[:b, :c], :conditions=>"id<5")
in end, rails executes this:
select `a`.* `a` inner join `b` on b.a_id = a.id inner join `c` on c.a_id = a.id ( id < 5 ) , ( (`a`.`type` = 'a1' ) )
which seems ok.
but again when try load b (like: <%= a.b.name %>
). excutes query.
so problem still exist.... :(
all need replace join
s includes
@datas = a.includes(:b, :c).where("id < 5")
note generate 1 query each association included. can reduce 1 single query forcing join using joins
@datas = a.joins(:b).includes(:b, :c).where("id < 5")
or can specify condition on 1 of associated models e.g.
@datas = a.includes(:b, :c).where(:b => {:column => value})
Comments
Post a Comment