【问题标题】:has_and_belongs_to_many query works in one direction, fails in the otherhas_and_belongs_to_many 查询在一个方向上工作,在另一个方向上失败
【发布时间】:2010-07-02 18:16:04
【问题描述】:

我有:

class Service < ActiveRecord::Base
  has_and_belongs_to_many :staffs

class Staff < ActiveRecord::Base
  has_and_belongs_to_many :services

使用带有列 services_id 和 staffs_id 的中间表 services_staffs

以下查询成功:

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

但是换个方向失败了:

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

服务负载 (0.3ms) SELECT "services".*, t0.staff_id as the_parent_record_id FROM "services" INNER JOIN "services_staffs" t0 ON "services".id = t0.service_id WHERE (t0.staff_id IN (12, 13,14)) 服务负载 (0.0ms) SQLite3::SQLException: 没有这样的列:staff_id: SELECT * FROM "services" WHERE (staff_id = 13)

ActiveRecord::StatementInvalid(SQLite3::SQLException:没有这样的列:staff_id: SELECT * FROM "services" WHERE (staff_id = 13)):

知道为什么吗??

【问题讨论】:

    标签: ruby-on-rails has-and-belongs-to-many


    【解决方案1】:

    我通常使用 has_many 然后通过,但是概念是一样的。您需要在搜索中包含关联,以便

    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 变量以帮助防止恶意代码攻击。

    【讨论】:

    • arg,我的错……应该是 staffs.staff_id 而不是 services.staff_id
    • 太棒了,明白了!再次感谢。就我而言,它实际上是“staffs.id = ?”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 2021-11-13
    • 1970-01-01
    • 1970-01-01
    • 2014-05-03
    • 1970-01-01
    相关资源
    最近更新 更多