I have the following two models Ads and Listings.
class Listing < ActiveRecord::Base
  belongs_to :ads
end
class Ad < ActiveRecord::Base
  has_many :listings
end
In my view to create a new ad, I used a listing partial, because I would 
like to use that listing partial in other parts of my project. So the 
view looks like:
<%= error_messages_for ''ad'' %>
<p><label for="ad_title">Title Ad</label><br/>
<%= text_field ''ad'', ''title'' 
%></p>
<p><label for="ad_text">Text</label><br/>
<%= text_area ''ad'', ''text'' 
%></p>
<%= render (:partial => "listing/listing", :object =>
@listing) %>
The view code of the listing partial is:
<p><label
for="listing_start_date">Startdatum</label>
<%= select_day (Time.now.day, :prefix => "listing") %>
<%= select_month (Time.now.month, :prefix => "listing") %>
<%= select_year (Time.now.year, :prefix => "listing",
:start_year =>
Time.now.year,
                  :end_year => Time.now.year+1) %>
</p>
<p><label for="listing_number_weeks">Aantal
weken</label>
<%= select (:listing, :number_weeks,
             [[''1 Week'', 1],
             [''2 Weken'', 2],
             [''3 Weken'', 3],
             [''4 Weken'', 4],
             [''5 Weken'', 5],
             [''6 Weken'', 6],
             [''7 Weken'', 7],
             [''8 Weken'', 8],
             [''9 Weken'', 9],
             [''10 Weken'', 10]]) %>
</p>
Adding a valid ad, with a correct listing works fine. The problem is 
when I try to add an ad with an invalid start date. It only save the 
data of the ad to the database and not that of the listing. I guessed it 
would raise an error and not add any data to the database. In my listing 
model I have added validation to validate the correctness of the date, 
like so:
  def validate
    if Date::valid_civil?(year.to_i, month.to_i, day.to_i) == nil
  	errors.add(:year, day.to_s + "-" + month.to_s + "-" +
year.to_s + "is
geen geldige datum.")
    else
  	self.start_date = year.to_s + "-" + month.to_s + "-" +
day.to_s
    end
  end
The validation works perfect if I only test the listing model without 
the integration in the ad model.
In my ad controller I create the ad like:
  def create
    @ad = Ad.new(params[:ad])
    @listing = Listing.new(params[:listing])
    @listing.listing_type = "ads"
    if @ad.save
      @ad.listings << @listing
      flash[:notice] = ''Ad was successfully created.''
      redirect_to :action => ''list''
    else
      render :action => ''new''
    end
  end
When I save my ad, how can I get Rails to also check for the correctness 
of the start date and raise an error if it is not valid? Hope somebody 
can give some pointers.
Kind regards,
Nick
-- 
Posted via http://www.ruby-forum.com/.