2016-12-03 38 views
1

我正在开发一个项目,允许客户在Ruby on Rails上预订(预订)酒店房间。我希望客户指定他想要的房间类型,并根据他的选择,我想显示此类房间列表。Ruby on Rails的collection_select更改取决于其他形式

<div class="form-group"> 
    <div class="control-label col-sm-5"> 
    <%= f.label :room_Type %> </div> 
    <div class="col-sm-6"> 
    <%= f.collection_select :room_type, Type.all, :id, :name, :prompt => true %></div></div> 
    <div class="form-group"> 
    <div class="control-label col-sm-5"> 
    <%= f.label :room_Number %> </div> 
    <div class="col-sm-6"> 
    <%= f.collection_select :room_id, Room.all, :id, :number, :prompt => true %> 
    </div></div> 

现在,我可以从数据库中显示房间类型列表。我也可以从数据库中显示房间列表。我做了一些关于这个的搜索,他们说可以使用JQuery或Ajax来完成,但我不知道该怎么做。你能帮我解决这个问题吗?

回答

0

该解决方案还可以帮助您了解流程。 首先你向你的控制器发出一个ajax调用。 (请记住,来自ajax调用的此URL必须存在于您的路由中)。

$(document).ready(function() { 
    $("#room_type").on('change', function(){ 
    $ajax({ 
     url: "populate_other_list", 
     type: "GET", 
     data: {room_type: $(this).val()}, 
     // Callbacks that will be explained 
    }) 
    }); 

接下来,在控制器中进行操作。

def populate_other_list 
    room_type = params[:room_type] 
    @room = Room.find_by room_type: room_type 
or  
    Pass Id from AJax of Type and find the room here from Type  
    @room = Type.find(params[:type_id).rooms // Call the association if exists  
    respond_to do |format| 
    format.json { render json: @room } 
    end 
end 

有了这个,你的Ajax调用你的成功回调,你得到你的列表中的JSON对象。所以你需要清除房间号码选择并创建选项并追加到它。

// Ajax call 
success: function(data) { 
    $("#room_id").children().remove(); 
    // Create options and append to the list 
} 
// Rest of Ajax call 

正如你所看到的,我没有把创造的选项像下面

由于其SIM [PLE的JavaScript可以很容易地找到计算器 对于暗示这将是外观代码

$("#room_id").append("<option>" + /your value/ + "</option>"); 
+0

谢谢你的好解释。我还有其他问题。我应该在哪里放置ajax调用(第一个)和ajax回调(成功后)。你的意思是我使用get来定义其他页面的路由中的url? – Adam

+0

是的,您需要在路由中将其定义为在assets/javascript目录中获取并写入代码。 –

+0

否则您可以使用预定义的rails ajax格式以及https://kernelgarden.wordpress.com/2014/02/26/dynamic-select-boxes-in-rails-4/参考它 –