Skip to content

Loading…

FormHelper is highly coupled (aka breaks without) to ActiveRecord #6415

Closed
hammerdr opened this Issue · 4 comments

3 participants

@hammerdr

Particularly, this line is that one that will break.

https://github.com/rails/rails/blob/4f66586bbfacbce4c07f2b9d8d142be1bf6d4e5e/actionpack/lib/action_view/helpers/form_helper.rb#L1412

However, if you take a look throughout the helper code you'll see that it is using persisted? in many, many places.

I'm not sure what the solution is, but this prevents us from using form_for to build a form for a non-AR (e.g. non-persisted, aggregate roots, data mapper pattern) model. If I implement the method persisted? in my model, everything works fine.

At the very least, we can be a little more lenient and ask if the object responds to persisted?, and if not assume :new

@rafaelfranca
Ruby on Rails member

Actually Form helpers are not coupled with Active Record. To a class work with it you need to implement the Active Model interface. You can see what are the requisites here. If you want to test if your class is implementing the interface you can use the Lint Tests

@hammerdr

Ah. Apologies. Just did ActiveModel::Naming (and there wasn't much in the way of docs for ActiveModel::Model, I guess)

@rafaelfranca
Ruby on Rails member

No problem. ActiveModel::Model is only present in the master branch, but you can look the implementation and use it in your application.

@carlosantoniodasilva
Ruby on Rails member

@hammerdr ActiveModel::Model was a small addition to Rails 4, but you don't need it to integrate with ActionPack helpers such as form_for. You can just include the modules it includes, implement the persisted? method, and you should be good to go (you don't even need the Validations module, it's just an add-on to ActiveModel::Model).

I think the best you can do is to use the Lint Tests as @rafaelfranca pointed out. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.