Saving data model is not validated


#1

I have the following two models Ads and Listings.

class Listing < ActiveRecord::Base
belongs_to :ads

#validate correctness of start_date
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
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’ %>
<%= error_messages_for ‘listing’ %>

Title Ad
<%= text_field 'ad', 'title' %>

Text
<%= text_area 'ad', 'text' %>

<%= render (:partial => “listing/listing”, :object => @listing) %>

The view code of the listing partial is:

Startdatum

<%= 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) %>

The validation for the start date of the listing works perfect if I test
the
listing model apart. Adding a valid ad, with a correct listing start
date
works fine. The problem is when I try to add an ad with an invalid start
date. It saves the ad to the DB, but doesn’t raise an error.

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 of the listing and raise an error if it is not valid?
Please
help me!!
BTW If you need more info to solve the issue, please contact me.

Kind regards,

Nick