根据rails中的用户选择获取数据库记录

时间:2013-04-06 01:44:51

标签: javascript ruby-on-rails database forms selection

我有一个充满值的“房间类型”表,我想这样做,当用户从collection_select中选择房间类型时,表单的其余部分会根据房间类型的值进行更新,我可以检测到使用javascript通过$('#room_roomtype_id')更改选择。更改以及通过$('#room_roomtype_id:selected')。text()选择了哪种房型,但我不知道,我的搜索时间一直无效,然后,如何使用房间类型表中的数据更新其他表单字段。

这是我的表单代码:

<%= 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 %>

1 个答案:

答案 0 :(得分:0)

这样的事情应该有效:

$('#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);
    });
});