Note that there are some explanatory texts on larger screens.

plurals
  1. PORails validating with two models
    primarykey
    data
    text
    <p>Ok, bit confused on how to solve this issue.</p> <p>I have one form and two models. Here is my form:</p> <pre><code>&lt;% if @booking.errors.any? %&gt; &lt;% @booking.errors.full_messages.each do |msg| %&gt; &lt;p class="error"&gt;&lt;%= msg %&gt;&lt;/p&gt; &lt;% end %&gt; &lt;% end %&gt; &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; &lt;%= form_for :booking, url: bookings_path do |f| %&gt; &lt;%= label_tag :email, "Guest's Email Address" %&gt; &lt;%= text_field_tag :email %&gt; &lt;%= f.label :nights, "Nights" %&gt; &lt;%= f.text_field :nights %&gt; &lt;%= f.label :nights, "People" %&gt; &lt;%= f.text_field :people %&gt; &lt;%= f.label :nights, "Arrival Date" %&gt; &lt;%= f.text_field :arrival %&gt; &lt;% end %&gt; </code></pre> <p>As you can see, the email field isn't part of the form builder. The email address will be used to create a new Guest record if the email doesn't already exist. Once I have the ID of the guest then the booking record can be made also.</p> <p>Here is the code for create action in my BookingController - where the form is submitted to...</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 render 'new' end end ... </code></pre> <p>I do realise this question isn't new but I can't find a good solution anywhere to my problem - I want to be able to set the form up properly (if necessary) and <strong>validate</strong> all fields using the two models. Then I need to display the error messages. At the moment, my email is ignored during validation and I'm not sure what to do next.</p> <p>Any help much appreciated.</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.
 

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