Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to set writeable dynamically? #40

Open
tangrufus opened this issue Apr 17, 2016 · 6 comments
Open

How to set writeable dynamically? #40

tangrufus opened this issue Apr 17, 2016 · 6 comments

Comments

@tangrufus
Copy link

tangrufus commented Apr 17, 2016

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!

@adis-io
Copy link

adis-io commented May 11, 2017

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

@apotonick
Copy link
Owner

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).

@adis-io
Copy link

adis-io commented May 11, 2017

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

Myform.new(MyModel.new)

or

Myform.new(MyModel.find(1))

@timoschilling
Copy link
Contributor

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

That should work for you.

@apotonick
Copy link
Owner

@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.

@oleg-kiviljov
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants