开发者

How to modify a record before saving on Ruby on Rails

Looking for a way to either:

  • Change one of the fields of a new record (namely - force it to lower-case) bef开发者_Python百科ore saving it to a RoR db. I've tried:

    before_create do |term| term.myfield.downcase! end

but this gives an error of:

undefined method `before_create' for RowsController:Class

or

  • Check that the field is all lowercase, and if not, raise an error message, and not create the record.

tried:

before_filter :check_lowcase, :only => [:new]
def check_lowcase
  if (Term.new =~ /[^a-z]+/)
    flash[:notice] = "Sorry, must use lowercase"
    redirect_to terms_path
  end
end

this seems to just be ignored....


You need to do it on your model, not your controller:

class YourModel < ActiveRecord::Base
 before_create :downcase_stuff

  private
    def downcase_stuff
      self.myfield.downcase!
     end
end


    before_create :lower_case_fields

    def lower_case_fields
       self.myfield.downcase!
    end


before_save { |classname| classname.myfield = myfield.downcase }

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜