[英]In Rails 5.1, how do I write a finder method for a has_many and then belongs_to association?
I'm using Rails 5.1.我正在使用 Rails 5.1。 I have the following models ...
我有以下型号...
class Member < ApplicationRecord
has_many :plans, :dependent => :nullify
class Plan < ApplicationRecord
belongs_to :associate
I want to write a finder query that returns all Member objects with a Plan that has an "associate" with an ID of "1", "2", or "3".我想编写一个查找器查询,该查询返回所有成员对象的计划,该计划具有 ID 为“1”、“2”或“3”的“关联”。 How do I do that?
我怎么做? I tried writing a finder for only finding the ID, "1", but am getting this error upon evaluation ...
我尝试编写一个仅查找 ID“1”的查找器,但在评估时出现此错误...
[8] pry(main)> Member.where(:plans => {:associate => {:id => "1"}}).count
(0.7ms) SELECT COUNT(*) FROM "Members" WHERE "associate"."id" IS NULL
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: missing FROM-clause entry for table "associate"
LINE 1: SELECT COUNT(*) FROM "members" WHERE "associate"."id" ...
^
: SELECT COUNT(*) FROM "members" WHERE "associate"."id" IS NULL
from /Users/davea/.rvm/gems/ruby-2.5.1/gems/activerecord-5.2.2.1/lib/active_record/connection_adapters/postgresql_adapter.rb:611:in `async_exec'
You must first use joins
to create an INNER JOIN
query.您必须首先使用
joins
来创建INNER JOIN
查询。 After that you're able to access the join tables:之后,您就可以访问连接表:
Member.joins(plans: :associate).where(associates: { id: 1 })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.