0

I am trying to capture validation errors for individual forms as I have many on one page.

I am giving each form its own unique id by using object_id

<% object = @document || Document.new %>
<%= form_for object, :html => { id: object.object_id.to_s } do |f| %>

But if i do this to capture errors the same error message will appear on all my forms

<% if object.errors.any? %>
  # errors
<% end %>

I have tried

<% if object.object_id.errors.any? %>

But i get

undefined method `errors' for 59187740:Fixnum

Is there a way around this please

Thanks

Edit

i have just noticed that the form id changes when validation fails as the page reloads, so that explains why the object cannot be found.

How can i keep the form id the same?

Richlewis
  • 15,070
  • 37
  • 122
  • 283

1 Answers1

0

If really depends on what you want to do with the errors:

You want to show them for each form:

<%= form_for some_object, do |f1| %>
  <%= f1.error_messages %>
  <%= # f1 magic %>

<%= form_for other_object, do |f2| %>
  <%= f2.error_messages %>
  <%= # f2 magic %>

You want to access them for each object:

just call object.errors: some_object.errors

What isn't working for you:

Calling object_id on an object access its id which is a number (FixNum). You are trying to call a method/access an attribute on a FixNum which does not exist.

You just want some persistent ID for your form

I assume that your object is coming from a database and already has an ID. So why don't you just use object.id? Every time Rails create an ActiveRecord object for you from the DB, that object gets a new object_id. So it is only logical that the ID doesn't stay the same since you have a new object in memory. Read more about it here:

https://stackoverflow.com/a/3430487/2295964

Community
  • 1
  • 1
Yan Foto
  • 10,850
  • 6
  • 57
  • 88
  • thanks for your answer..Is there a way to assign a number to the form id (maybe iterate through an array), so that when the form fails validation say, the same id will be assigned.. My problem is when creating a new object – Richlewis Jan 28 '15 at 22:04
  • @Richlewis can you provide more information about how your forms are created and structured? – Yan Foto Jan 28 '15 at 22:41
  • What else would you like to see? – Richlewis Jan 30 '15 at 06:33