我尝试在周计划中添加许多小时,所以我编码: #应用程序/模型/ week_plan.rb 类WeekPlan< ApplicationRecord has_many:小时 accepts_nested_attributes_for:小时 端
# app/model/hour.rb
class Hour < ApplicationRecord
belongs_to :weekplan
end
# app/controllres/weekplan_controller.rb
class WeekplansController < ApplicationController
def new
@weekplan = WeekPlan.new
7.times { @weekplan.hours.build }
end
private
def set_weekplan
@weekplan = WeekPlan.find(params[:id])
end
def weekplan_params
params.require(:weekplan).permit(hours_attributes: [ :date_start ])
end
end
最终, app / views / weekplans / new.html.rb
<h1>New Plan</h1>
<%= form_for @weekplan do |f| %>
<%= f.fields_for :hours do |hour| %>
<p>
<%= f.label :user_id %><br>
<%= f.select :user_id, User.all.collect { |p| [ p.name, p.id ] }, include_blank: true %>
</p>
<p>
<%= f.label :date %><br>
<%= f.datetime_field :date %>
</p>
<p>
<%= f.label :date_start %><br>
<%= f.datetime_field :date_start %>
</p>
<p>
<%= f.label :date_end %><br>
<%= f.datetime_field :date_end %>
</p>
<% end %>
<%= f.submit %>
<% end %>
但是,当我运行我的应用程序时,我收到错误:
(undefined method `user_id' for #<WeekPlan id: nil, created_at: nil, updated_at: nil>):
我无法理解,一个bug隐藏在哪里?
答案 0 :(得分:4)
您应该在hour.label
:
hour.select
,fields_for :hours
等
f.fields_for :hours do |hour| %> # <======= hour was not used, use it
<p>
<%= hour.label :user_id %><br> # <======= hour, not `f`
<%= hour.select :user_id, User.all.collect { |p| [ p.name, p.id ] }, include_blank: true %>
# same with all other nested object's fields
P.S。 Ruby数据的Ruby处理很糟糕:
User.all.collect { |p| [ p.name, p.id ]
使用db:
User.pluck(:name, :id)