disposable icon indicating copy to clipboard operation
disposable copied to clipboard

How to set writeable dynamically?

Open tangrufus opened this issue 8 years ago • 6 comments

How to set writeable dynamically? (with a block / lambda or...)

Tried these, all act as writeable: true no matter what's in the model

module User
  module Contract
    class Update < Reform::Form
      property :nickname, writeable: -> { model.nickname.blank? }
      property :address, writeable: model_nickname_blank?
      property :phone, writeable: :model_phone_blank

      def model_nickname_blank?
          model.nickname.blank?
      end

      def model_phone_blank
          model.phone.blank?
      end
    end
  end
end

Thanks!

tangrufus avatar Apr 17 '16 23:04 tangrufus

How can I set writable = true on new model and and writable = false on persisted model?

adis-io avatar May 11 '17 05:05 adis-io

You need two different twins, that's the idea, to treat different contexts (create vs. update) with different classes and not one big mess the way AR handles it (or doesn't).

apotonick avatar May 11 '17 07:05 apotonick

@apotonick The thing is I'm using reform, where I can do this:

Myform.new(MyModel.new)

or

Myform.new(MyModel.find(1))

adis-io avatar May 11 '17 08:05 adis-io

property :nickname, writeable: -> { model.persisted? }

That should work for you.

timoschilling avatar May 11 '17 08:05 timoschilling

@adisos Reform doesn't care whether you use it for updating or creating things. It's your job as a software engineer to decide if you want to "hack" it (see last messages) or if you need a new contract to separate. I'd totally go with @timoschilling's solution if it was only one field, but extract a separate Update contract when it gets more.

apotonick avatar May 11 '17 08:05 apotonick

I tried @timoschilling solution but seems that it does not actually execute the lambda, did someone try it? Using disposable 0.4.4

oleg-kiviljov avatar Apr 25 '19 10:04 oleg-kiviljov