我有两个模型的Rails 4应用程序。如何验证子记录的数量?
class User
has_many :bids
end
class Bid
belongs_to :user
end
用户只能每周创建一个投标,所以我增加了以下至投标表
add_column :bids, :expiry, :datetime, default: DateTime.current.end_of_week
及以下范围至投标模型
scope :default, -> { order('bids.created_at DESC') }
scope :active, -> { default.where('expiry > ?', Date.today) }
我可以现在阻止用户在控制器级别创建多个出价,如下所示:
class BidsController
def new
if current_user.bids.active.any?
flash[:notice] = "You already have an active Bid. You can edit it here."
redirect_to edit_bid_path(current_user.bids.active.last)
else
@bid = Bid.new
respond_with(@bid)
end
end
end
但是在模型层面验证这一点的最佳方法是什么?
我一直在尝试设置自定义验证,但我一直在努力查看最佳方法来设置此值,以使current_user可用于该方法。另外,我是否将错误添加到正确的对象?
class Bid
validate :validates_number_of_active_bids
def validates_number_of_active_bids
if Bid.active.where(user_id: current_user).any?
errors.add(:bid, "too much")
end
end
end