ruby on rails - How to validate the number of children records? -
i have rails 4 app 2 models.
class user has_many :bids end class bid belongs_to :user end
a user can create 1 bid per week, added following bid table
add_column :bids, :expiry, :datetime, default: datetime.current.end_of_week
and following scopes bid model
scope :default, -> { order('bids.created_at desc') } scope :active, -> { default.where('expiry > ?', date.today ) }
i can prevent user creating multiple bids @ controller level so:
class bidscontroller def new if current_user.bids.active.any? flash[:notice] = "you have active bid. can edit here." redirect_to edit_bid_path(current_user.bids.active.last) else @bid = bid.new respond_with(@bid) end end end
but best approach validating @ model level?
i've been trying set custom validation, struggling see best way set current_user available method. also, adding errors correct object?
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
in order maintain separation of concerns, keep current_user knowledge out of model layer. bid model has user_id attribute. also, i'd add error since validation not checking "bid" attribute on bid, rather entire bid may invalid.
class bid validate :validates_number_of_active_bids def validates_number_of_active_bids if bid.where(user_id: user_id).active.any? errors[:base] << "a new bid cannot created until current 1 expires" end end end
Comments
Post a Comment