Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>It seems to me that the easiest way to is to validate the email in the controller itself and add any validation error to the booking variable. Something like this:</p> <pre><code>def create accommodation = current_user.accommodation guest = Guest.find_or_create_by(:email =&gt; params[:email]) @booking = accommodation.bookings.new(post_params.merge(:guest_id =&gt; guest.id)) if @booking.save flash[:success] = 'The booking has been added successfully.' redirect_to :controller =&gt; 'bookings', :action =&gt; 'index' else &lt;% if params[:email].blank&gt; %&gt; @booking.errors.add(:email, "can't be blank.") &lt;% end %&gt; #You can do the same thing for whatever other validation errors you have render 'new' end end </code></pre> <p><strong>Note:</strong> I did not test the code </p> <p>This is probably not the best way possible but it gets the job done and is easy. You could use accept_nested_attributes_for but it seems to me a little bit unnecessary considering that you are only validating an email. Nevertheless, if you want to do it the cleanest way, stick with accept_nested_attributes_for.</p> <p><strong>EDIT</strong></p> <p>Actually, your code is the right track. You just made a syntax error. The real reason your guests errors are not being shown is that you used a local variable instead of a instance variable. Try this:</p> <pre><code>@guest = Guest.find_or_create_by(:email =&gt; params[:email]) </code></pre> <p>Your error messages should be displayed with the code you already have</p> <pre><code>&lt;% if @guest.errors.any? %&gt; &lt;% @guest.errors.full_messages.each do |msg| %&gt; &lt;p class="error"&gt;&lt;%= msg %&gt;&lt;/p&gt; &lt;% end %&gt; &lt;% end %&gt; </code></pre> <p><strong>EDIT 2</strong></p> <p>In order to avoid a booking instance from beings saved in case the guest email is invalid you can do something like this:</p> <pre><code>if !@guest.errors.any? &amp;&amp; @booking.save flash[:success] = 'The booking has been added successfully.' redirect_to :controller =&gt; 'bookings', :action =&gt; 'index' else </code></pre> <p>Therefore, if the guest has any errors, the if statement will terminate before the @booking.save statement is executed.</p>
    singulars
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      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