Validating model data from another controller in Rails

I have two tables: Customer (number, name, ...)
Purchase (id, item, date, client_id, ...)

They have a corresponding model with their validation. I need to create a new customer with a new purchase, all in the client controller create method. Something like that:

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 the purchase 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, by validating in the model, from the client controller? And how can I rollback a new client created on errors?

Yes, I can make the validation as the very first statement in a regex method, but I find it ugly. I feel like there might be a normal method to do this check, or even do things differently (i.e., call the create method on the Purchase from Client controller).

Can you get me back on track?

Thanks in advance.

+1


source to share


2 answers


Take a look at the next page working with associations .

Rails provides you with several convenience methods for your objects.

As shown below:

Client.purchases.empty?
Client.purchases.size,
Client.purchases
Client.purchases<<(purchase)
Client.purchases.delete(purchase)
Client.purchases.find(purchases_id)
Client.purchases.find_all(conditions)
Client.purchases.build
Client.purchases.create

      



When using these methods, you are using validations on each of the models.

Go to the Rails console and create a new client and try any of the above methods. You will quickly find out how strong they are and you will soon be on your way.

Edit: Here's a much better guide to Rails associations!

+2


source


Depends a little on the situation, but you can use validates_associated to run validation on related objects. Then you can create a user (but not save), create a purchase (but not save) and try to save the user. If you've done this correctly, the user won't be able to store the validation error on the linked object.



+1


source







All Articles