Rails:fields_for 和集合

发布于 2024-10-07 07:53:10 字数 475 浏览 5 评论 0原文

我想为 fields_for 使用额外的集合。这个集合应该包含在 fields_for 中使用的所有可能性。

假设我有一个人,他的任务每周都会在同一天定期发生。在人员表单中,即使还没有任何保存的任务,我也应该每天都有一个条目。我尝试过:

<% form_for(@person) do |f| %>
...

  <% f.fields_for :tasks, @weekdays do |task_fields| %> 
    <%= weekday.name %>: 
    <%= project_fields.text_field :name %>
  <% end %>
<% end %>

现在每个工作日都应该有一个文本字段来输入当天任务的名称。例如 weekday.name =“星期一”和task.name =“喝咖啡”,task.weekday_id = 1

i would like to use an additional collection for a fields_for. this collection should hold all the possibilities to be used in fields_for.

Lets say I have a person with tasks that will happen regularly each week on the same day. In the person form, i should have an entry for each day, even if there are not yet any saved tasks. I tried:

<% form_for(@person) do |f| %>
...

  <% f.fields_for :tasks, @weekdays do |task_fields| %> 
    <%= weekday.name %>: 
    <%= project_fields.text_field :name %>
  <% end %>
<% end %>

now there should be for each weekday a text field to enter the name of the task of that day. for example weekday.name = "monday" and task.name = "drinking coffee", task.weekday_id = 1

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

清音悠歌 2024-10-14 07:53:10

您没有迭代 week_days。你应该这样做:

<% @weekdays.each_with_index do |weekday, i| %>
  <% f.fields_for :tasks do |task_fields| %> 
    <%= weekday.name %>: 
    <%= task_fields.text_field :name %>
    <%= task_fields.hidden_field :weekday_id, :value => (i + 1) %>
  <% end %>
<% end %>

如果你有一个表“weekdays”,那么hidden_​​field值应该是weekday.id

编辑:7月30日

我想我完全搞砸了这个答案。让我尝试改进它。

<% f.fields_for :tasks, @weekdays do |task_fields| %> 
  <%= weekday = task_fields.object %>
  <%= weekday.name %>: 
  <%= task_fields.text_field :name %>
  <%= task_fields.hidden_field :weekday_id, :value => weekday.id %>
<% end %>

You are not iterating through the week_days. You should do like this:

<% @weekdays.each_with_index do |weekday, i| %>
  <% f.fields_for :tasks do |task_fields| %> 
    <%= weekday.name %>: 
    <%= task_fields.text_field :name %>
    <%= task_fields.hidden_field :weekday_id, :value => (i + 1) %>
  <% end %>
<% end %>

If you have a table 'weekdays', then hidden_field value should be weekday.id

Edit: July 30

I think I completely messed up this answer. Let me try to improve it.

<% f.fields_for :tasks, @weekdays do |task_fields| %> 
  <%= weekday = task_fields.object %>
  <%= weekday.name %>: 
  <%= task_fields.text_field :name %>
  <%= task_fields.hidden_field :weekday_id, :value => weekday.id %>
<% end %>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文