【问题标题】:Rails 3.2 Ajax Update Div when Text Field Populated Many to Many Form当文本字段填充多对多表单时,Rails 3.2 Ajax 更新 Div
【发布时间】:2012-06-24 22:04:36
【问题描述】:

最后,我想要一个将 client_id 传递给部分的文本字段。我想异步执行此操作,以便在更新文本字段值时,shipping_products 部分会动态更改。最好的方法是什么?

在 index.html.erb 中

<!-- Text Field Here-->
<div id="available_products">
  <%= render "shipment_products" %>
</div>

在 _shipment_products.html.erb 中

<div id="shipment_products_container">
  <h3>Assign Products to Ship<\h3>
  <ul class="shipment_products" id="shipment_products">
    <% Product.by_client(client_id).each do |product|%>  <!-- TextField value passed here -->
      <%= content_tag_for :li, product, :value => product.id do %>
        <%= hidden_field_tag("shipment[product_ids][]", product.id) %>
        <%= product.product_name %>
      <% end %>
    <% end %>
  <\ul>
</div>

模型关系:

Models and Relationships
  Shipment  has_many :products :through => :shipment_products
  Product   has_many :shipments :through => :shipment_products
  ShipmentProducts belongs_to :shipment,  belongs_to :product
  Product belongs_to :client
  Client has_many :products

这和我最终想要的差不多。

【问题讨论】:

    标签: ruby-on-rails ajax jquery ruby-on-rails-3.1


    【解决方案1】:

    由于我不知道您的控制器中有什么以及如何制作路线,因此我提出了一些建议。把一些东西改成实际的。我假设您不需要更改index 操作(如果只是添加respond_to js)

    index.html.erb

    <%= form_tag shipment_path, remote: true do %> - points to index action
      <%= text_field_tag :client_id %>
      <%= submit_tag :load %>
    <% end %>
    <div id="available_products">
      <%= render "shipment_products" %>
    </div>
    

    index.js.erb

    $('#available_products').html("<%= j render "shipment_products" %>");
    

    【讨论】:

    • 如何将客户端 id text_field 的值传递给部分中的 by_clients 方法?如果说 jQuery 模糊事件,我该怎么做?
    • 1.在您的控制器中index 操作:@client = Client.find(params[:client_id])。现在,您可以在您的部分中使用 @client E.g. Product.by_client(@client.id)。 2.$('.my-super-form').submit();
    【解决方案2】:

    我认为您应该为此使用嵌套模型概念,请参考-

    http://railscasts.com/episodes/197-nested-model-form-part-2?view=asciicast

    【讨论】:

    • 我终于想通了。由于赏金明天结束,我将成为一个好公民并奖励你赏金。给你一个提升的代表。你的答案比另一个答案好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-18
    • 2018-02-27
    • 1970-01-01
    • 1970-01-01
    • 2012-11-05
    相关资源
    最近更新 更多