Forum: Ruby on Rails Saving data model is not validated

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
91308e9bc88cb069fd1bcf88e910d042?d=identicon&s=25 Nick Snels (nicksnels)
on 2005-12-08 08:37
(Received via mailing list)
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' %>

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

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
This topic is locked and can not be replied to.