first post on the RoR mailinglist. Yet another problem I can’t figure
out. Here goes:
I have the following two models Ads and Listings.
class Listing < ActiveRecord::Base
class Ad < ActiveRecord::Base
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’ %>
<%= text_field 'ad', 'title' %>
<%= text_area 'ad', 'text' %>
<%= render (:partial => “listing/listing”, :object => @listing) %>
The view code of the listing partial is:
<%= select_day (Time.now.day, :prefix => “listing”) %>
<%= select_month (Time.now.month, :prefix => “listing”) %>
<%= select_year (Time.now.year, :prefix => “listing”, :start_year =>
:end_year => Time.now.year+1) %>
Aantal weken <%= 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]]) %>
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:
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.”)
self.start_date = year.to_s + “-” + month.to_s + “-” + day.to_s
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:
@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
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 helpful pointers. Thanks.