Rails新手在这里。我坚持使用Rails中的fields_for,并且会永远感激任何人的帮助。
我正在尝试创建和查看表单,其中每个事件为每个朋友都有2个字段。
_form.html.erb:
<%= form_for(@event) do |f| %>
<div class="field">
Date: <%= f.text_field :date %></br>
Friends: <%= f.fields_for :friends do |friends_fields| %>
<%= friends_fields.text_field :name %>
<% end %>
<% end %>
index.html.erb:
<tbody>
<% @events.each do |event_form| %>
<tr>
<td><%= event_form.date %></td>
<td><%= event_form.friends.each do |friend| %>
<%= friend.name %>
<% end %>
</td>
<td><%= link_to 'Show', event %></td>
<td><%= link_to 'Edit', edit_event_path(event) %></td>
<td><%= link_to 'Destroy', event, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
event.rb:
class Event < ActiveRecord::Base
has_many :friends
accepts_nested_attributes_for :friends, allow_destroy: true
end
friend.rb:
class Friend < ActiveRecord::Base
belongs_to :event
end
events_controller.rb:
def new
@event = Event.new
2.times { @event.friends.build }
end
答案 0 :(得分:0)
事件未定义,因为事件迭代器在每次迭代中使用event_form而不是事件变量名。尝试改为:
<tbody>
<% @events.each do |event| %>
<tr>
<td><%= event.date %></td>
<td><%= event.friends.each do |friend| %>
<%= friend.name %>
<% end %>
</td>
<td><%= link_to 'Show', event %></td>
<td><%= link_to 'Edit', edit_event_path(event) %></td>
<td><%= link_to 'Destroy', event, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>