0

我是 Rails 的新手,正在寻找通往 Rails 的道路。

现在我正在寻找在我的表单中使用来自相关模型的值的方法。例如,我创建了两个具有 *has_one* 关系的模型。主表“产品”有一个字段“unit_id” - 来自相关表“单位”的项目的 ID。

澄清:模型产品中的项目具有属性“单元”。一种产品有一个属性单元。模型单元中的项目是唯一的,一个项目单元可能属于产品中的多个项目。

在我的表单中,我想为新产品选择单位,我可以打开单位#index 的表单,但是我如何返回并使用调用者表单中的选定项目?

代码片段:

一、模型产品:

class Product < ActiveRecord::Base
# ... 
 belongs_to :unit
end

2. 型号单位:(无代码)

class Unit < ActiveRecord::Base
end

3. 相关表格请求使用模板:

<%= form_for(@product) do |product_form| %>
  ...
  <%= product_form.label :"#{t('unit')}:"%>
  <%= link_to t('unit_select'), units_path%>
  ...
 <div class="actions">
  <%= product_form.submit %>
 </div>
<% end %>

4. 带有单位索引的表格模板,我想从中选择:

<%@units.each do |unit|%>
 <a href="<%=units_path%>">
  <div>
   <%= unit.shortname %>
   <%= unit.fullname %>
   <%= unit.okei %>
  </div>
 </a>
<%end%>

我的问题是:我必须怎么做?我如何返回和使用单位表中的选定项目?

PS对不起我的英语。PPS I have example images, but no have the reputaion for include them to my question: https://plus.google.com/photos/101112417211111476248/albums/5848798001333173089/5889575276122513954?banner=pwa&pid=5889575276122513954&oid=101112417211111476248

https://plus.google.com/photos/101112417211111476248/albums/5848798001333173089/5889575270731602306?banner=pwa&pid=5889575270731602306&oid=10111241721111147624

4

1 回答 1

0

我会给你3个不同的选择:

1 - 最好的解决方案是在您的表格中包含单位列表,然后选择 IMO。更易于实施并为用户提供更好的体验。

2 - 在您的表单中添加一个 hidden_​​field product_form.unit_id。然后你可以使用http://lokeshdhakar.com/projects/lightbox2/来显示单元并添加一个javascript,当用户点击一个单元时,它将关闭灯箱并使用单元的id更新 hidden_​​field 值

3 - 在单位页面中添加一个指向单位的链接,该链接将重定向到传递 unit_id 参数的表单页面,然后在控制器中执行以下操作@product.unit = Unit.find(params["unit_id"] if params["unit_id"].present?:但是这样你会丢失以前更改的数据,当然不是一个好的解决方案

于 2013-06-15T06:41:15.477 回答