开发者

Modifying a rails model at runtime

on a previous question, I was searching for a way to dynamic valitating my models.

Advice on "Dynamic" Model validation

The solution that I got working is:

def after_initialize        
  singleton = class << self; self; end

  validations = eval(calendar.cofig)

  validations.each do |val|
    singleton.class_eval(val)
  end
end

On my actual app, I have 2 models

class Calendar < ActiveRecord::Base
  has_many :events
end

class Event < ActiveRecord::Base
  belongs_to :calendar

  def after_initialize        
    singleton = class << self; self; end

    validations = eval(calendar.cofig)

    validations.each do |val|
       singleton.class_eva开发者_如何学JAVAl(val)
    end
 end

end

As you can see, the validation code that should be added to the Event class lies on the Calendar field "config".

Works fine for a existing Event, but doesn't for a new record. That's because, at the time that after_initialize is called, the association doesn't exists yet.

I can't find a way to do that besides putting the config values on Event itself.

Any advices?

Tks!


You probably want to run your validation code during the validation phase, not the initialize phase. Try this:

class Calendar < ActiveRecord::Base
  has_many :events
end

class Event < ActiveRecord::Base
  belongs_to :calendar

  validate do |event|
    validations = eval(calendar.cofig)
    validations.each do |val|
      eval(val)
    end
  end
end
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜