[英]Write a single rails active record query to get all the items by association with two tables?
我有三个表,如供应商,位置,技术,以及两个关联表,如vendor_location,vendor_technology。
关联如下
vendor.rb
has_many :vendor_technologies
has_many :vendor_locations
has_many :locations, through: :vendor_locations
has_many :technologies, through: :vendor_technologies
location.rb
has_many :vendor_locations
has_many :vendors, through: :vendor_locations
technology.rb
has_many :vendor_technologies
has_many :vendors, through: :vendor_technologies
vendor_location.rb
belongs_to :location
belongs_to :vendor
vendor_technology.rb
belongs_to :technology
belongs_to :vendor
从上表中,我需要
1) vendors in locations (india)
need: list of vendors
2) vendors in technology (php)
need: list of vendors
3) vendors in technology and location (php and india)
need: list of vendors
对于上述要求,我需要三个单查询而不使用联接操作。 因为,join需要更多的内存(供应商表有12列)
为什么要维护这么多表,我们可以像这样简单地做:
#vendor.rb
has_many :locations
has_many :technologies
#location.rb
belongs_to :vendor
#technology.rb
belongs_to :technology
现在只加载一次供应商列表:
@vendors = Vendor.includes(:locations, :technologies)
现在,根据您的条件获取所需的数据。这里很棒的事情是根据您的条件获取数据不会触发任何额外的查询。
@vendors.first.locations.select {|x| x.place == 'India' }
@vendors.first.technologies.select {|x| x.tech_name == 'PHP' }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.