Ruby on rails 基于Rails中的另一个表更新数量
这真的很简单,但我的头撞到墙上了。用户可以订阅教育节目,但订阅数量有限。我想做的是根据创建/销毁方法从总数中扣除/返回总数。因此,我有以下模型:Ruby on rails 基于Rails中的另一个表更新数量,ruby-on-rails,Ruby On Rails,这真的很简单,但我的头撞到墙上了。用户可以订阅教育节目,但订阅数量有限。我想做的是根据创建/销毁方法从总数中扣除/返回总数。因此,我有以下模型: User has_many :requests scope :managers, -> {where(azure_manager: true) } Training has_many :requests validates :name, uniqueness: true, presence: true validates :subscripti
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
还使用所有验证更新了模型 你能把你的问题编辑得更具体一点吗(你得到的是一个错误,还是一个意外的结果?如果是,是什么?)。另外,如果您可以发布您的培训和请求模型,您是否想过改变逻辑并使用计数器缓存?您不必自己维护计数器,并且可以在创建新请求时检查是否
training.requests\u count
。令人沮丧的是,我必须为Azure使用一些Oauth,这会导致服务器出现一些问题,因此我无法快速测试。我是个n00b高手,不知道如何在pry中测试。你有什么问题?您使用回调的思维过程是做您想做的事情的正确方法。