Nesting forms in Rails is a common practice where one form

As a newcomer to web development, I'm looking for some guidance! I've set up a page where Rails fetches room data from the database and displays it in a table. Everything is going smoothly, but I want to enable users to click a button next to each row to book a room.

Currently, it's working about 80% of the way. However, I've encountered an issue where I have a form nested within another form, causing the booking action to apply to the last row in the table. I've read about potential solutions involving JavaScript, but as a beginner, I'm not well-versed in JavaScript.

One workaround could involve placing the Reservation.new form inside the all_rooms form, which might resolve the issue. However, I also need to obtain the datetimepicker value from the user. That's why I initially placed it outside the form.

<%= form_for(Reservation.new, remote: true, format: :js, url: {controller: "booker", action: "create"}) do |new_res| %>
  <div class="calender">
    <%= new_res.date_field :date, :value => (Time.now + 6.days).strftime('%Y-%m-%d') ,  min: 6.days.from_now, max: 90.days.from_now %>
  </div>
  <div class="time">
    <%= new_res.time_select :start_time , {:default => {:hour => 10 , :minute => 00}, minute_step: 15 , :start_hour => 8, :end_hour => 18, :hour => 11} %>
    <%= new_res.time_select :end_time , {:default => {:hour => 14 , :minute => 00}, minute_step: 15 , :start_hour => 8, :end_hour => 18, :hour => 11} %>
  </div>

</div>
<div class="t_Data">
  <table class="rooms_to_book">
    <tr>
      <th>Name</th>
      <th>Size</th>
      <th>Building</th>
      <th>Equipment</th>
      <th>Book</th>
    </tr>
    <% @all_rooms.each do |r| %>
      <tr>
        <td><%= r.room %></td>
        <td><%= r.room_size %></td>
        <td><%= r.building %></td>
        <td><%= r.room_description %></td>
        <td>
          <%= new_res.hidden_field :room, value: r.room %>
          <%= new_res.hidden_field :building, value: r.building %>
          <%= new_res.hidden_field :room_size, value: r.room_size %>
          <%= new_res.hidden_field :room_description, value: r.room_description %>
          <%= new_res.submit  "Book" %>
        </td>
      </tr>
    <% end %>
  </table>
</div>
<% end %>

My question is this: how can I resolve the issue so that when a user clicks 'Book', a new reservation is created with all the relevant data, including the user-selected date, specific to each row?

Answer №1

Rather than using hidden fields, you can give each submit button a specific name like this:

<%= reserve.submit  "Confirm Reservation", name: room_id %>

Subsequently, in your controller's create action, you can retrieve the room id from the params hash which will serve as a reference to "Confirm Reservation". With this id, you can locate the corresponding Room object and proceed to create a new Reservation with all the details from the hidden fields.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to click a button on HTML file

In my current project, there is a piece of code responsible for checking if the user is logged in or not. If the user hasn't logged in yet, they are redirected to the login page. Once the user logs in successfully, they should be able to upload conten ...

Encountering a problem with the Ionic Modal Slider: unable to locate the matching element associated with delegate-handle= when using $

I am encountering a problem with my Ionic application that features multiple Angular controllers. Specifically, I have a LoginCtrl and RegisterCtrl controller set up. The issue arises when I try to trigger a modal with a slider from the RegisterCtrl by usi ...

Setting up Geolocation

I have been utilizing an APM tool for my work. The tool currently requires a pop-up in order to capture the user's location. However, there is now a need to capture the user's location without the pop-up appearing. Is there a method or workaroun ...

Clicking two times changes the background

I am facing an issue with three boxes on my website. Each box is associated with a corresponding div. When I click on any box, the div displays and the background color turns red. However, when I click on the same box again, the div disappears but the back ...

Guide on displaying the AJAX response in CakePHP 3.1

I'm working with a table that contains checkboxes. After selecting them, I want to calculate the sum of values from the table in a modal before confirming the form submission. Can someone guide me on how to render the AJAX response from the controller ...

Different ways to resize an image in various sizes without relying on PHP thumb

I have developed an admin panel for managing reservations of charter, yacht and other vehicles. I am looking for a solution to upload only one image per vehicle and resize it in multiple sizes without relying on the phpthumb library due to its slow loadi ...

Using a locally hosted HTML page to update a JSON file stored on my computer

In my current project, I need to reorganize data stored in an array named unknown. Each item in this array needs to be moved either to a new array called good or another one called bad. let data = { "bad":[], "unknown": ["b", "a", "d", "g", "o", ...

Is there a way to trigger an AJAX request right before I leave the page or unload it?

When the window is about to be unloaded, an AJAX request is sent to a specific URL including the recent tracking ID and the time spent on the page in seconds. However, the behavior I am experiencing is an alert displaying [object Object]. ...

Manipulating JSON Elements using JavaScript in HTML

My objective is to alternate the visibility between the "prev" and "ext" elements retrieved from the JSON File in the following manner: Here is the link to JS Fiddle The menu bar appears as follows: [ "prev_Person1" "Person1" "ext_Person1" ... "Person2" ...

Place the retrieved data from the API directly into the editor

I've integrated the LineControl Editor into my app and everything is functioning perfectly, except for when I attempt to insert text into the editor. Here's the link to the LineControl GitHub page: https://github.com/suyati/line-control/wiki Fo ...

What is the best way to display the outcome in a popup window?

I am looking to display the result in a pop-up window. Code: <?php $con=mysqli_connect("localhost","root","1234","fyp"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $result = ...

What is the best way to play a random song when the user clicks a button?

My goal is to develop a website where users can click on an image and have a random song play from a playlist. I currently have a functioning code that activates one song, but it fails when adding multiple songs to the mix. <html> <head> ...

Connecting two COTURN servers for seamless communication

Currently, I have a total of 5 webRTC peers connected through the COTURN server (turnServer1). These peers are all behind symmetric NAT, requiring the use of the TURN server to establish connections. However, due to the media streams with audio and video b ...

Creating a banner image that scrolls while maintaining a fixed size

I'm looking to add a banner image with a scrolling effect as users navigate down the page, but I'm not sure what this technique is called. An example of what I'm trying to achieve can be seen on this site. As the user scrolls down, the res ...

When attempting to upload a picture using the camera, the file upload process is unsuccessful

Whenever I attempt to upload an image from my existing files, everything goes smoothly. However, if I try to select a file by directly clicking on the camera icon on my mobile device, it fails with a "CORS Error" message. I have tried adding and removing t ...

Click on the navigation bar buttons to toggle between different divs and display multiple information boxes simultaneously

Here is the current code snippet... $("#contact").click(function() { if ( $( "#contact_div" ).length ) { $("#contact_div").remove(); } else { var html='<div id="contact_div" class="contact-info"><p>Contact info</p&g ...

Adding a fresh HTML element to a list at a designated location

I found this excellent example on CODEPEN Is there a way to insert a new random number into the list so that it appears after 24 but before 19? Is there an efficient solution or do I need to manually check each li element and determine where to place the ...

The type 'myInterface' cannot be assigned to the type 'NgIterable<any> | null | undefined' in Angular

I am facing an issue that is causing confusion for me. I have a JSON data and I created an interface for it, but when I try to iterate through it, I encounter an error in my HTML. The structure of the JSON file seems quite complex to me. Thank you for yo ...

Passing a custom Vue component as a property to a parent component

Struggling to find answers to my unique question, I'm attempting to create an interface where users can drag or input images using Vue. I've developed a component called Card, which combines Vue and Bulma to create card-like objects with props fo ...

Troubleshooting issues with calculator operators in JavaScript for beginners

As a beginner in JavaScript, I've taken on the challenge of building a calculator to enhance my skills. However, I'm having trouble getting the operator buttons (specifically the plus and equal buttons) to function properly. Can someone please as ...