rails中每个项目的表单



如何通过每个对象创建动态表单?我的搜索解决方案有利于SEO。

我有这样的HTML:

<% @products[0..2].each do |p| %>
<div class="catalog-item">
<img class="catalog-item__img" src="https://via.placeholder.com/150">
<h2 class="catalog-item__title"><%= p.name %></h2>
<select name="" class="input input-container__input">
<%= p.product_prices.each do |pp| %>                
<option value=""><%= pp.weight %> kg - <%= pp.price %> USD</option>
<% end %>
</select>
<input type="date" name="" class="input input-container__input">
<%= link_to "Details", details_path(p.id), class: "btn", remote: true %>
<%= link_to 'Add', add_to_cart_path(p.id), class: 'btn btn--icon', remote: true %>
</div>
<% end %>

我曾经这样尝试过:

<% @products[0..2].each do |p| %>
<% form_for $product do |f| %>
<div class="catalog-item">
<img class="catalog-item__img" src="https://via.placeholder.com/150">
<h2 class="catalog-item__title"><%= p.name %></h2>
<select name="whatsname?" class="input input-container__input">
<%= p.product_prices.each do |pp| %>                
<option value=""><%= pp.weight %> kg - <%= pp.price %> USD</option>
<% end %>
</select>
<input type="date" name="" class="input input-container__input">
<%= link_to "Details", details_path(p.id), class: "btn", remote: true %>
<%= link_to 'Add', add_to_cart_path(p.id), class: 'btn btn--icon', remote: true %>
</div>
<% end %>
<% end %>

但是我不知道如何从多个表单访问数据。当生成对象时,我不知道product对象中应该有什么

您的代码有问题。您当前使用的form_for被破坏了,因为您传递了错误的对象:您应该使用p,因为这是当前迭代中的对象。(你似乎没有定义$product,所以如果你把那个对象传递给form_for,因为它是nil,所以事情根本不会起作用。)

另外,请停止尝试手动构建表单,并使用Rails帮助程序。阅读精细的手册。Rails表单工作得很好,使一切都很简单,但是,与Rails的所有内容一样,如果您希望事情正常工作,则需要使用框架。如果你在框架之外工作,你真的需要知道你在做什么,因为否则你就会一直与Rails作斗争——如果你要这样做,为什么还要使用Rails呢?

如果你不确定你在处理什么(@products,p,无论什么),尝试使用byebuggem并添加断点并检查变量的状态。

===修改注释

在注释(!)中进行了大量的探索之后,看起来您想要这样的代码:

<% @products.each do |product| %>
<%= form_with scope: product.name, url: PATH_TO_FORM_ENDPOINT do |form| %>
<%= form.label :prices, "Prices for #{product.name}" %>
<%= form.select :prices, product.product_prices.to_a %>
<%= form.hidden_field :id, value: product.id %>
<%= form.submit %>
<% end %>
<% end %>

这将产生一系列单独的表格,每个产品一个,列出可用的价格。显然,因为你没有在你的应用程序中共享数据结构或路由,你需要相应地更新代码,但希望这能给你一些想法。

(将范围添加到表单中可以确保每个表单都以不同的方式命名,以便在用户提交表单时可以区分它们。在每种情况下,url可能是相同的。并且,希望您能够看到Rails表单帮助程序如何使编写表单变得更加简单!)

最新更新