Adding validations without knowing the fields

Posted by Frexuz on Stack Overflow See other posts from Stack Overflow or by Frexuz
Published on 2010-06-07T13:38:34Z Indexed on 2010/06/07 13:42 UTC
Read the original article Hit count: 152

Filed under:
|

My example form

<% form_for @ad do |f| %>
  <%= f.error_messages %>
  <p>
    <%= f.label :ad_type_id %><br />
    <%= f.collection_select(:ad_type_id, AdType.all, :id, :name) %>
  </p>
  <p>
    <% @ad.ad_properties.each do |property| %>

      <%= property.name %>:
      <% f.fields_for :ad_values do |value_field| %>
        <%= value_field.text_field :ad_id, :value => @ad.id %>
        <%= value_field.text_field :ad_property_id, :value => property.id %>
        <%= value_field.text_field :value %>
      <% end %><br /><br />

    <% end %>
  </p>
  <p>
    <%= f.label :description %><br />
    <%= f.text_area :description %>
  </p>
  <p><%= f.submit %></p>
<% end %>

Explanation:
Ad has many properties. I can add new properties at any time (it's a normal model).
Lets say the Ad is of the type 'hotel'. Then I would add properties like 'stars' and 'breakfast_included'
Then I store each of these properties' values in a separate model.
And all this works fine with my form above.

My problem:
These fields are not validated because I can't know what their names are.
I need to add validations dynamically somehow.

My thought:

#Before the normal validations kick in
def add_validations
  self.properties.each do |property|
    property.add_validation :whatever #somehow :)
  end
end

How could I do this?

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about validation