说实话,这很简单,但是我把头撞在墙上。用户可以订阅教育计划,但是订阅数量有限。我想要做的是基于创建/销毁方法从总数/返回值减去总数。所以我有以下模型:
User
has_many :requests
scope :managers, -> {where(azure_manager: true) }
Training
has_many :requests
validates :name, uniqueness: true, presence: true
validates :subscriptions_available, numericality: { greater_than_equal_to: 1, less_than_or_equal_to: 100 }
has_attached_file :avatar,
styles: {
large: ['304>x304>', :png],
medium: ['225>x225>', :png],
small: ['112>x112>', :png]
}
Requests
belongs_to :user
belongs_to :training
has_many :approvals, dependent: :destroy
由于请求控制了创建/销毁,因此将以下代码放入控制器:
after_create :remove_from_sub
after_destroy :return_to_sub
def create
@requests = Request.create(request_params)
respond_with @requests
end
def remove_from_sub
training.subscriptions_available -= self.subscriptions_available
training.save
end
def return_to_sub
training.subscriptions_available += self.subscriptions_available
training.save
end
我的问题是会影响培训表和数量的两种方法。如何正确点击该属性?
编辑: 我意识到我什至没有准确地绘制训练模型,所以我将其切换为:
def remove_from_sub
@traininge = Training.find_by(params[:id])
@training.subscriptions_available -= self.subscriptions_available
@training.save
end
def return_to_sub
@training = Training.find_by(params[:id])
@training.subscriptions_available += self.subscriptions_available
@training.save
end
还使用所有验证更新了模型。