我有一个User对象和一个通过HABTM连接表关联的Orgs对象。我想在更新Orgs对象并将Org.approved值设置为true时向用户发送电子邮件。我在组织上有一个批准的布尔值。
我想我已经完成了大部分工作,但我需要帮助实际发送电子邮件的步骤。
这是我的代码
class OrgMailer < ApplicationMailer
default from: 'myemail@example.co'
def org_approved(user, org)
@user = user
@orgs = User.orgs.all
@url = 'http://example.com/login'
mail(to: @user.email, subject: 'Your listing has been approved.')
end
end
User.rb
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
has_and_belongs_to_many :orgs, join_table: :orgs_users
end
Org.rb
class Org < ApplicationRecord
has_and_belongs_to_many :users, join_table: :orgs_users
# after_update :send_approved_listing_email, only: [:update]
attachment :company_image
def send_approved_listing_email
OrgMailer.org_approved(i).deliver_now if org.approved === true
end
end
更新:已添加ORG_CONTROLLER
我已经编辑了我的代码,看起来像下面的答案,但我现在收到一个新错误:未初始化的常量Org :: OrgsUser
当我点击@ org.users&lt;&lt;&lt;&lt;&lt;&lt;创建动作中的@user行。
如果我删除此行,我就可以创建一个组织,但它没有正确关联。
org_controller.rb
class OrgsController < ApplicationController
before_action :set_org, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!
def index
@orgs = Org.all
@tags = ActsAsTaggableOn::Tag.all
end
def show
end
def new
@org = Org.new
end
def contest
end
def edit
end
def create
@user = current_user
@org = Org.new(org_params)
@org.users << @user
respond_to do |format|
if @org.save
format.html { redirect_to thankyou_path, notice: 'Your listing was successfully created. Our team will approve your listing after review.' }
format.json { render :show, status: :created, location: @org }
else
format.html { render :new }
format.json { render json: @org.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if @org.update(org_params)
format.html { redirect_to @org, notice: 'Listing was successfully updated.' }
format.json { render :show, status: :ok, location: @org }
else
format.html { render :edit }
format.json { render json: @org.errors, status: :unprocessable_entity }
end
end
end
def destroy
@org.destroy
respond_to do |format|
format.html { redirect_to orgs_url, notice: 'Listing was successfully destroyed.' }
format.json { head :no_content }
end
end
def tagged
if params[:tag].present?
@orgs = Org.tagged_with(params[:tag])
else
@orgs = Org.postall
end
end
private
def set_org
@org = Org.find(params[:id])
end
def org_params
params.require(:org).permit(:twitter, :linkedin, :facebook, :name, :offer, :offercode, :url, :descrption, :category, :approved, :company_image, :tag_list => [])
end
end
我在管理员面板中使用主动管理员,并有批量操作来更新任何选定的组织并批准它们。我认为我缺少的是在send_approved_listing_email方法中,我需要遍历组织并在组织批准时通过电子邮件发送给每个用户。
目前在更新时没有任何反应,所以我确定我没有正确地执行此操作。我错过了什么?我该怎么写呢?
答案 0 :(得分:0)
我会为连接表创建一个模型,而不是使用habtm。这样,您可以在保存连接对象时使用回调:
q.allSettled