How to override “new” method for a rails model

后端 未结 7 722
南笙
南笙 2020-12-16 03:01

In my rails app I have a model with a start_date and end_date. If the user selects Jan 1, 2010 as the start_date and Jan 5, 2010 as the end_date, I want there to be 5 instan

7条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-16 03:49

    Don't override initialize It could possibly break a lot of stuff in your models. IF we knew why you needed to we could help better ( don't fully understand your explanation of the form being a skeleton, you want form attributes to create other attributes?? see below). I often use a hook as Marcel suggested. But if you want it to happen all the time, not just before you create or save an object, use the after_initialize hook.

    def after_initialize
      # Gets called right after Model.new
      # Do some stuff here
    end
    

    Also if you're just looking for some default values you can provide default accessors, something like: (where some_attribute corresponds with the column name of your model attribute)

    def some_attribute
      attributes[:some_attribute] || "Some Default Value"
    end
    

    or a writer

    def some_attribute=(something)
      attributes[:some_attribute] = something.with_some_changes
    end
    

    If I understand your comment correctly, it looks like you expose a form that would make your model incomplete, with the other attributes based on parts of this form? In this case you can use any of the above methods after_initialize or some_attribute= to then create other attributes on your model.

提交回复
热议问题