Forum: Ruby on Rails Get errors from one model show up in the view of another mod

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Nick S. (Guest)
on 2005-12-07 22:37
(Received via mailing list)

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
  belongs_to :ads

class Ad < ActiveRecord::Base
  has_many :listings

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' %>

<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 (, :prefix => "listing") %>
<%= select_month (, :prefix => "listing") %>
<%= select_year (, :prefix => "listing", :start_year =>,
                  :end_year => %>

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

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.")
  	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:

  def create
    @ad =[:ad])
    @listing =[:listing])
    @listing.listing_type = "ads"

      @ad.listings << @listing
      flash[:notice] = 'Ad was successfully created.'
      redirect_to :action => 'list'
      render :action => 'new'

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.

Kind regards,

This topic is locked and can not be replied to.