Ruby on Rails Thursday, January 26, 2012

On 26 January 2012 17:16, Colin Law <clanlaw@googlemail.com> wrote:
> Then have a validation in the Duck model
> that prevents the duck from being saved if its owner already has his
> max allowance.

It would probably just annoy people if they were not told until they'd
entered all their "new duck" requirements that they'd reached their
limit. So I'd also keep a permissions-type check in the controller
too. As Colin says the code to check for this is in the model, so can
be re-used by the permissions check and the validation.


class DucksController < AR:Base
before_filter :check_duck_limit, :only => [:new, :create]

def new
@duck = Duck.new
end

private
def check_duck_limit
flash[notice: "You have reached your limit. Upgrade your plan."]
if current_user.reached_duck_limit?
end
end

class User < AR:Base
validate :has_duck_availability

def reached_duck_limit?
self.ducks.count >= self.max_number_of_ducks
end

# in case a user can not yet have a plan, it's handy to make sure
it exists, and return a safe value
def max_number_of_ducks
plan ? plan.max_number_of_ducks || 0 : 0
end

private
def has_duck_availability
errors.add(:duck_count, "has been reached") if reached_duck_limit?
end
end


PS you don't need to assign "current_user" to an instance variable -
just use current_user ;-)

PPS Your current code alerts when the limit is exceeded, rather than reached

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

No comments:

Post a Comment