开发者

rails: fields_for and collection

开发者 https://www.devze.com 2023-01-30 01:50 出处:网络
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.

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.开发者_Python百科 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


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 %>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号