我的嵌套属性有什么问题?

What's wrong with my nested attributes?

我尝试在周计划中增加很多小时,所以我编码: #app/models/week_plan.rb class 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?

您应该在 fields_for :hours:

中使用 hour.labelhour.select
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 数据库数据处理错误:

User.all.collect { |p| [ p.name, p.id ]

为此使用数据库:

User.pluck(:name, :id)