2016-12-15 1 views
0

는 내가 코드, 그래서 weekplan에 많은 시간을 추가하려고 : # 응용 프로그램/모델/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 

그리고 finnaly, 응용 프로그램/뷰/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>): 

버그가 숨겨진 부분을 이해할 수 없습니까?

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 

추신 :

+0

네,하지만 나는 ** ** week_plans에 필요하지 않습니다 : 그것을 위해

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

사용 DB는 : DB 데이터의 루비 처리가 나쁘다 ** user_id ** 열이 있습니다. – Valentin

답변

4

당신은 hour.label, hour.selectfields_for :hours 내부를 사용해야합니다 때문에 ** 시간 **

User.pluck(:name, :id) 
+0

추가 질문이 있습니다. http://stackoverflow.com/questions/41203572/nested-attributes-do-not-save-child 내 자녀 모델이 저장되지 않았습니다. – Valentin

관련 문제