views:

34

answers:

2

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?

A: 

Have you tried with polymorphic associations ? That's maybe a cleaner approach.

http://railscasts.com/episodes/154-polymorphic-association

benoror
A: 

Disclaimer: I've never done this before, so I'm not 100% sure it will work.

But as long as you can get the type of the object you are working with, you can use the Rails constantize method to get the model it references (I'm assuming that if ad can be of type Hotel, then you have a Hotel model). At that point you should probably have the appropriate validations on your Hotel model.

Zachary
That's the thing. I don't have a model for every AdType. I want to be able to add new types to that table, and then just add new AdProperties for that new type. Building a structure through administration basically :)
Frexuz