#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2003
    Posts
    174
    Rep Power
    12

    Calling model methods even when the param is a not set


    Hello,
    I'm setting a checkbox values based on the return of a model field method. The way the method is set up - it only gets called when a checkbox value is set.

    Here's the model code:

    Code:
      def within=(new_within)
         @within = new_within == "1" || new_within == true || new_within == 'true' || new_within == 'on'
      end
    I would like that method to be called even when the checkbox is not set.

    Thanks for any help anyone can provide.

    Clem C
  2. #2
  3. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Location
    Woodland Hills, Los Angeles County, California, USA
    Posts
    9,625
    Rep Power
    4247
    You're not going to get that method called when the value is not set in the checkbox. That's because the HTTP protocol will not send the field value if the checkbox is not set. The solution is to

    1. Set the underlying model's default value to 0 for the field, so when you create a new instance, the default is set.

    2. Check if model.within is set after you've set the other values and then set it yourself, if it isn't:
    Code:
    model = Model.new(params[:model])
    if model.within.nil?
        model.within = 0
    end
    model.save
    3. Override the new method for your model and make it set the value of model.within first before updating with all the passed in params.
    Up the Irons
    What Would Jimi Do? Smash amps. Burn guitar. Take the groupies home.
    "Death Before Dishonour, my Friends!!" - Bruce D ickinson, Iron Maiden Aug 20, 2005 @ OzzFest
    Down with Sharon Osbourne

    "I wouldn't hire a butcher to fix my car. I also wouldn't hire a marketing firm to build my website." - Nilpo

IMN logo majestic logo threadwatch logo seochat tools logo