1

I have two models, Tenant and Property. Property has many Tenants, and Tenant belongs to Property.

I want to write a validation that validates the presence of a tenant unless the property is vacant. This is my code:

validates :tenants, :presence => true, :unless => :vacant?

It seems to make sense, but I can still add a tenant to a property having already stated it as vacant. I'm not sure what other code you'd need to see.

<% @properties.each do |property| %>
<tr>
    <td><%= property.street_address %></td>
    <td><%= property.city %></td>
    <td><%= property.postcode %></td>
    <td><%= display_vacant(property) %></td>
    <td><%= property.tenants.collect(&:first_name).to_sentence %></td>
    </tr>
<% end %>

As always, thanks for any feedback.

Edit: I'm not allowed to post images because I'm a new user, but here's a visual representation of what I want http://cl.ly/202r3j1c1Y1C2d2s0F1R

Raj
  • 22,346
  • 14
  • 99
  • 142
Delete
  • 21
  • 5
  • How you try add your tenant ? – shingara Feb 21 '12 at 12:18
  • 1
    Are you defining `vacant?` as an attribute on property? Seems like it would be better as a method `tenants.empty?`, which would remove the need for this validation completely. – Tom Whatmore Feb 21 '12 at 12:31
  • @shingara When you view a property there is an option to add a tenant to that property using a form. Sorry if that's not what you meant, I am quite new to this. – Delete Feb 21 '12 at 14:55
  • @TomWhatmore Yes, I am, but if tenants.empty? is an easier alternative then I will explore that avenue. Thanks :) – Delete Feb 21 '12 at 14:56
  • 1
    If vacant represents the state of a property having no tenants then it is definitely better to have the code explicitly reflect that, rather than setting a boolean elsewhere and then trying to enforce it via validations. If vacant represents something different then it should probably be named differently. – Tom Whatmore Feb 21 '12 at 15:09

0 Answers0