我想在注册项目(具有类别和合格的受众)后向创建警报的每个用户(具有相同类别和一个合格的受众)发送电子邮件。
模型
class Project
belongs_to :category
belongs_to :fondation
has_many :project_eligibles
has_many :eligibles, through: :project_eligibles
end
class Category
has_many :projects
has_many :alerts
end
class ProjectEligible
belongs_to :project
belongs_to :eligible
end
class Publication
belongs_to :user
belongs_to :category
belongs_to :eligible
end
class User
has_many :favorites
has_many :favorite_projects, through: :favorites, source: :favorited,
source_type: 'Project'
has_many :publications
end
MAILER
class ProjectMailer < ApplicationMailer
def newproject(project)
@project = project
proj_elig = ProjectEligible.where('project_id =?', project.id).pluck(:eligible_id)
mails = User.includes(:publications).where("publications.eligible_id IN (?) AND publications.category_id = ?", proj_elig, project.category_id).pluck(:email)
mail(
to: mails,
subject: "A new project for you !"
)
end
end
CONTROLLER(项目)
class ProjectsController < ApplicationController
def create
@project = Project.new(project_params)
@project.save
if @project.save
ProjectMailer.newproject(@project).deliver_now
redirect_to projects_path
else
render :new
end
end
private
def project_params
params.require(:project).permit(:title, :description, :link, :expiration,
:all_tags, :category_id, :fondation_id, eligible_ids: [])
end
end
ProjectMailer适用于类别,但不适用于project_eligible。 例如,如果用户希望在创建带有category_id 1和qualified_id 1的项目后立即收到电子邮件:
#<Publication:0x007fe089425010
id: 17,
user_id: 1,
category_id: 1,
eligible_id: 1,
created_at: Sun, 04 Nov 2018 17:08:52 UTC +00:00,
updated_at: Sun, 04 Nov 2018 17:08:52 UTC +00:00>
我创建一个项目:
Project.create!(
title: "test title",
description: 'sample description',
expiration: "2018-11-14",
category_id: 1 ,
fondation_id: 1,
eligible_ids: [1,2]
)
如果我检查: 项目已创建:
#<Project id: 481, title: "test title", description: "sample description", link: nil, expiration: "2018-11-14", category_id: 1, fondation_id: 1, created_at: "2018-11-13 09:15:01", updated_at: "2018-11-13 09:15:01">
但是project_eligibles很奇怪,没有保存:
#<ActiveRecord::Associations::CollectionProxy [#<ProjectEligible id: nil, project_id: nil, eligible_id: 1, created_at: nil, updated_at: nil>, #<ProjectEligible id: nil, project_id: nil, eligible_id: 2, created_at: nil, updated_at: nil>]>
所以proj_elig为空:[]
但是之后,如果在终端机中,我检查了Project.last.project_eligibles
:
我找到了我的项目(id:398),其中包含2个合格的ID(分别为1和2):
[#<ProjectEligible:0x007fe08d010d40
id: 398,
project_id: 481,
eligible_id: 2,
created_at: Tue, 13 Nov 2018 09:15:01 UTC +00:00,
updated_at: Tue, 13 Nov 2018 09:15:01 UTC +00:00>,
#<ProjectEligible:0x007fe08d010048
id: 397,
project_id: 481,
eligible_id: 1,
created_at: Tue, 13 Nov 2018 09:15:01 UTC +00:00,
updated_at: Tue, 13 Nov 2018 09:15:01 UTC +00:00>]
是否有project_eligible记录相对于项目被延迟了,因此在ActionMailer中始终将其视为空?
我如何确保project_eligibles已注册且proj_elig不为空?
谢谢您的建议!我有点迷路了。。。