繁体   English   中英

Rails动态表单-带有SimpleForm参数的调用控制器来更新页面

[英]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.

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