2

I'm currently developing an Rails app (rails v5.1.1 and ruby v2.3.4) and I'm getting an error when trying to use a reform form object at one of my routes (/bookings/new):

undefined method `persisted?' for #<Booking:0x007fbae9a98138>

I'm using a virtus model (which works fine on other contexts):

class Booking
  include Virtus.model

  attribute :id, Integer
  attribute :client_email, String
end

This is my form object:

class BookingForm < Reform::Form
  property :client_email
end

This is the new action on my controller:

def new
  @form = BookingForm.new(Booking.new)
end

This is my form partial:

<%= form_for @form do |form| %>
  <%= form.text_field :client_email %>

  <div class="actions">
    <%= form.submit %>
  </div>
<% end %>

I thought using a virtus model instead of an active record one should be no issue since reform sells itself as Form objects decoupled from your models. Did I get anything wrong?

Igor_Marques
  • 1,742
  • 2
  • 16
  • 24
  • you could just define `def persisted?` in your `Booking` class, and use whatever logic you want there, you could just return `false` if the class will only represent new objects. – fanta Jul 03 '17 at 16:47
  • This does not seem to be the proper approach since I'd also need to implement a `to_key` method at my Booking model (to return the elements of the form). After that I get the error: `undefined method `input' for #` (at the line of my input). – Igor_Marques Jul 03 '17 at 16:51
  • there are many things you can use, for instance `ActiveModel::Conversion`(http://api.rubyonrails.org/classes/ActiveModel/Conversion.html) gives you the `persisted?` method plus some others. You could also use `ActiveModel::Naming`(http://api.rubyonrails.org/classes/ActiveModel/Naming.html) in case you need it. – fanta Jul 03 '17 at 16:56
  • Oops, I actually made a mistake by using the `form.input` method instead of `form.text_field`. My bad. But the `ActiveModel::Conversion` inclusion actually solved my issue! Thank you – Igor_Marques Jul 03 '17 at 17:01

1 Answers1

0

It seems like the comment from @fanta helped, but I the long-term answer is that you should avoid using Virtus, especially since you are building a new project. Virtus is no longer supported by it's own team, they moved on to dry-rb ( dry-types and dry-validations)

If you need to mock a model - you can use dry-struct, OpenStruct, etc

Also Reform now has full support for dry-validation and dry-types, and it is going to be the way of the future ( thou AM is going to be supported till version 4) Best of luck :-)

konung
  • 6,908
  • 6
  • 54
  • 79