简体   繁体   中英

Fetching database records based on user selection in rails

I have a "room type" table full of values, I want to make it so that when a user selects a room type from the collection_select the rest of the form gets updated with that room type's values, I can detect when the selection is changed with javascript through $('#room_roomtype_id').change and which room type was selected through $('#room_roomtype_id :selected').text() but I have no idea, and my hours of searching have been futile, how to then update the other form fields with data from the room type table.

Here is my form code:

<%= form_for @room do |f| %>
        <% if @room.errors.any? %>
            <div class="error_messages">
                <h2>Form is invalid</h2>
                <ul>
                    <% for message in @room.errors.full_messages %>
                        <li><%= message %></li>
                    <% end %>
                </ul>
            </div>
        <% end %>

        <p id="roomtypes", data-url="<%= url_for :controller => 'rooms', :action => 'roomtypeupdate' %>">
            <%= f.label :roomtype_id, "Room type" %><br />
            <%= f.collection_select :roomtype_id, Roomtype.order(:name), :id, :name, include_blank: true %>
        </p>
        <p>
            <%= f.label :number, "Room number" %><br />
            <%= f.text_field :number %>
        </p>
        <p>
            <%= f.label :maxcap, "Capacity" %><br />
            <%= f.number_field :maxcap %>
        </p>
        <p>
            <%= f.label :size, "Size" %><br />
            <%= f.number_field :size %>
        </p>
        <p>
            <%= f.label :description, "Description" %><br />
            <%= f.text_area :description %>
        </p>
        <p>
            <%= f.label :singlebeds, "Number of single beds" %><br />
            <%= f.number_field :singlebeds %>
        </p>
        <p>
            <%= f.label :bathrooms, "Number of bathrooms" %><br />
            <%= f.number_field :bathrooms %>
        </p>
        <br />

        <p class="button"><%= f.submit %></p>
    <% end %>

Something like this should work:

$('#room_roomtype_id').on('change', function () {

    // URL for the sake of example - yours will differ
    $.get('/rooms/' + this.value + '.json', function (response) {

    // dummy response for the sake of example
    response = {
        "number": "5A",
        "maxcap": "10"
    };

    $.each(response, function (key, value) {
        $('[name="room[' + key + ']"]').val(value);
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM