我在Rails 4中遇到ActiveRecord查询问题:
我的模特:
class Addressee < ActiveRecord::Base
has_and_belongs_to_many :emails
end
class Email < ActiveRecord::Base
belongs_to :author, foreign_key: :from_id, class_name: "Addressee"
has_and_belongs_to_many :addressees
end
my schema.rb
create_table "addressees", force: true do |t|
t.string "token", limit: nil
t.string "domain", limit: nil
t.string "email", limit: nil
t.string "name", limit: nil
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "addressees_emails", force: true do |t|
t.integer "addressee_id"
t.integer "email_id"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "emails", force: true do |t|
t.string "message_id", limit: nil
t.integer "from_id"
t.string "subject", limit: nil
t.text "body"
t.datetime "date"
t.datetime "created_at"
t.datetime "updated_at"
end
我的查询:
# Returns correct emails
query_params = { "addressees.email" => "test@example.com" }
@emails = Email.includes(:addressees).where(query_params).references(:addressees)
我的问题:
# Returns only the addressee matching the email from query params
@emails.last.addressees
#<ActiveRecord::Associations::CollectionProxy [#<Addressee id: 12, token: "test", domain: "example.com", email: "test@example.com", name: nil, created_at: "2014-09-25 14:06:34", updated_at: "2014-09-25 14:06:34">]>
#Returns the wrong count
@emails.last.addressees.size
#=> 1
#Returns the correct count (because it does a new query)
@emails.last.addressees.count
#=> 3
我的问题:
如何修改查询以包含所有收件人而无需进行其他查询?我将@emails var传递给我的json序列化器,现在它只包含1个收件人而不是全部3个。
答案 0 :(得分:0)
@emails = Email.where('emails.id IN SELECT(email_id FROM addressees_emails WHERE addressee_id IN (SELECT id FROM addressees WHERE email IN (?)))', %w[test@example.com test2@example.com]).includes(:addressees)