[英]Rails Dynamic Form - call controller with the SimpleForm params to update the page
我正在開發一個頁面,用戶可以在其中創建新產品 。
每個產品都有一個產品模型 ,其中包含一些字段,如:id
, :name
, :description
等。
在此產品頁面中,我有一個<select>
,用戶可以在其中選擇產品型號 。 我想要做的是,當用戶選擇產品模型時 ,頁面應該更新,顯示選定的產品模型詳細信息。
一個人怎么能做到呢?
您可以使用javascript進行操作的示例(基於選擇更改):
首先為ProductModel
自定義方法定義一個集合路由。 讓我們把它find
:
resources :product_models do
get 'find', on: :collection #=>output: /product_models/find/:id
end
在ProductModelsController
使find
方法響應js格式:
def find
@product_model = ProductModel.find(params[:id])
respond_to { |format| format.js }
end
假設您有jQuery,則在application.js
(或所需的其他自定義js文件)中,創建ajax調用以查找product_model:
$(document).on('turbolinks:load', function() {
$('#product_product_model_id').on('change', function(){ //<-- the id selector is returned by simple_form
$.ajax({
type: "GET",
url: "/product_models/find/?id=" + $(this).val(),
success: function(data) {
},
error: function(jqXHR) {
console.error(jqXHR.responseText);
}
})
})
})
在您的Product
new視圖中的表單下,渲染一個部分名稱,例如,“ selected_product_model”:
#new.html.erb
<% simple_form_for @product do |f| %>
#... the form
f.association :product_model
<% end %>
<div>
<%= render partial: 'selected_product_model' %>
</div>
然后在partial中,創建將在其中顯示數據的html選擇器:
#_selected_product_model.html.erb
<p id="pm-id"></p>
<p id="pm-name"></p>
<p id="pm-desc"></p>
然后創建您的find.js.erb
文件(在views> product_models文件夾中)以在select更改時更新您的部分內容:
# @product_model comes from the controller find#product_models
$('#pm-id').html("ID: <%= j @product_model.id.to_s %>")
$('#pm-name').html("Name: <%= j @product_model.name %>")
$('#pm-desc').html("Description: <%= j @product_model.description %>")
當然,這只是可以在Rails中使用ajax的基本示例,您可以自定義顯示數據的方式或添加一些條件來防止錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.