Note that there are some explanatory texts on larger screens.

plurals
  1. POValidating data of a model from another controller in Rails
    primarykey
    data
    text
    <p>I have two tables: Client(id,name,...)<br> Purchase(id,item,date,client_id,...)</p> <p>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:</p> <pre><code>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 =&gt; "new" } format.xml { render :xml =&gt; @client.errors, :status =&gt; :unprocessable_entity } end flash[:notice] = 'You have a new client!' format.html { redirect_to(:action =&gt; :show, :id =&gt; @evento.id) } format.xml { render :xml =&gt; @client, :status =&gt; :created, :location =&gt; @client } else format.html { render :action =&gt; "new" } format.xml { render :xml =&gt; @evento.client, :status =&gt; :unprocessable_entity } end end end </code></pre> <p>In Purchase's model I have:</p> <pre><code>belongs_to :client validates_format_of :date, :with =&gt; /^20[0-9]{2}[-][0-9]{2}[-][0-9]{2}$/, :message =&gt; 'not valid' validates_presence_of :date </code></pre> <p>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?</p> <p>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).</p> <p>Can you put me back in the right way?</p> <p>Thank you in advance.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload