Hi all,
I have two tables:
Client(id,name,...)
Purchase(id,item,date,client_id,...)
They have their respective Model, with their validations. What I need is to create a new client with a new purchase, all into the create method of Client controller. Something like this:
def create
@client = Client.new(params[:client])
respond_to do |format|
if @client.save
# Add purchase
@sell = Purchase.new
@sell.client_id = @client.id
@sell.date = params[:date]
# Fill another fields
if @sell.save
# Do another stuff...
else
format.html { render :action => "new" }
format.xml { render :xml => @client.errors, :status => :unprocessable_entity }
end
flash[:notice] = 'You have a new client!'
format.html { redirect_to(:action => :show, :id => @evento.id) }
format.xml { render :xml => @client, :status => :created, :location => @client }
else
format.html { render :action => "new" }
format.xml { render :xml => @evento.client, :status => :unprocessable_entity }
end
end
end
In Purchase's model I have:
belongs_to :client
validates_format_of :date, :with => /^20[0-9]{2}[-][0-9]{2}[-][0-9]{2}$/, :message => 'not valid'
validates_presence_of :date
And there is my problem: how can I validate the date input, through validations into the model, from Client controller? And, how can I rollback the new client created when errors?
Yes, I can do the check as the very first instruction in the method, with a regular expression, but I think it's ugly. I feel like might exist a conventional method for doing this validation or even doing all the stuff in another way (i.e. calling create method for Purchase from Client controller).
Can you put me back in the right way?
Thank you in advance.