代码之家  ›  专栏  ›  技术社区  ›  99miles

多个查询在一个方向上工作,在另一个方向上失败

  •  1
  • 99miles  · 技术社区  · 15 年前

    我有:

    class Service < ActiveRecord::Base
      has_and_belongs_to_many :staffs
    

    class Staff < ActiveRecord::Base
      has_and_belongs_to_many :services
    

    以下查询成功:

    Staff.find( :all, :conditions => "service_id = #{service_id}" )
    

    Service.find( :all, :conditions => "staff_id = #{staff_id}" )
    

    具有

    服务加载(0.3ms)选择“服务”.*,t0.staff\u id作为“服务”上的“服务”内部连接“服务\u staff”t0的\u父记录\u id。id=t0.Service\u id WHERE(t0.staff\u id IN(12,13,14))服务加载(0.0ms)SQLite3::SQLException:无此列:staff\u id:SELECT*FROM“服务”WHERE(staff\u id=13)

    ActiveRecord::StatementInvalid(SQLite3::SQLException:没有这样的列:staff\u id:SELECT*FROM“services”WHERE(staff\u id=13)):

    知道为什么吗??

    1 回复  |  直到 15 年前
        1
  •  2
  •   Geoff Lanotte    15 年前

    我平时用的有很多然后通过,但概念是一样的。您需要在搜索中包含关联,因此

    Service.find( :all, :include => :staffs, :conditions => "staffs.id = #{staff_id}" )
    

    这将做一个外部连接,因此将包括所有服务,并将加载人员数据。

    Service.find( :all, :joins => :staffs, :conditions => "staffs.id = #{staff_id}" )
    

    service.staffs

    对于未经请求的建议,我建议稍微修改一下您的查询。

    Service.all(:include => :staffs, :conditions => ["staffs.id = ?", staff_id])
    

    阵法逃过你的视线 staff_id 变量来帮助防止恶意代码攻击。