has_and_belongs_to_many 查询在一个方向有效,在另一个方向失败
我有:
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) ):
知道为什么吗?
I have:
class Service < ActiveRecord::Base
has_and_belongs_to_many :staffs
and
class Staff < ActiveRecord::Base
has_and_belongs_to_many :services
With the intermediate table services_staffs with columns services_id and staffs_id
The following query succeeds:
Staff.find( :all, :conditions => "service_id = #{service_id}" )
But going the other direction fails:
Service.find( :all, :conditions => "staff_id = #{staff_id}" )
with
Service Load (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)) Service Load (0.0ms) SQLite3::SQLException: no such column: staff_id: SELECT * FROM "services" WHERE (staff_id = 13)
ActiveRecord::StatementInvalid (SQLite3::SQLException: no such column: staff_id: SELECT * FROM "services" WHERE (staff_id = 13) ):
Any idea why??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我通常使用 has_many 然后通过,但概念是相同的。您需要在搜索中包含关联,因此
这将执行外部联接,因此将包含所有服务并立即加载员工数据。
这将执行内部联接并且仅具有服务数据集(如果您调用
service.staffs
来获取未经请求的建议,则必须转到数据库,我建议稍微修改您的查询。
该数组会转义您的
staff_id
变量有助于防止恶意代码攻击。I normally use has_many and then through, but the concept is the same. You need to include the association in the search so either
This will do an outer join so will include all services and will eager load the staff data.
This will do an inner join and only have the service datasets (it will have to go to the database if you call
service.staffs
for unsolicited advice, I recommend modifying your query a bit.
The array escapes your
staff_id
variable to help to prevent malicious code attacks.