2017-01-20 1 views
0

이상한 문제가 있습니다. 나는 직원에 관련된 모든 작업을 표시하기 위해 노력하고있어, 나는 이해하지 못하는 오류가 :조인 테이블의 요소 표시

  • 내가 할 수있는 작업의 ID 만 액세스

내 코드 =

직원 지수 :

<% @staffs.each do |staff| %> 
    <tr> 
    <td> 
     <%= link_to staff.name, staff %> 
    </td> 
    <%staff.tasks.each do |task| %> 
     <td> 
     <%= task.id %>/
     </td> 
    <%end%> 
    </tr> 
<% end %> 

직원 컨트롤러 :

class StaffsController < ApplicationController 
    before_action :authenticate_user! 
    skip_before_action :configure_sign_up_params 
    before_action :set_staff, only: [:show, :edit, :update, :destroy] 

    # GET /staffs 
    # GET /staffs.json 
    def index 
    @staffs = current_user.staffs 
    end 


    private 
    # Use callbacks to share common setup or constraints between actions. 
    def set_staff 
     @staff = Staff.find(params[:id]) 
    end 

    # Never trust parameters from the scary internet, only allow the white list through. 
    def staff_params 
     params.require(:staff).permit(:name, :user_id) 
    end 
end 

직원 모델 :

class Staff < ActiveRecord::Base 
    has_one :user 
    has_many :ranches_staff 
    has_many :ranches, through: :ranches_staff 
    has_many :staffs_task 
    has_many :tasks, through: :staffs_task 
    accepts_nested_attributes_for :tasks, :allow_destroy => true 
end 
+0

오류를 추가 할 수 있습니까? Staff 모델도 추가 할 수 있습니다. – Ursus

+0

안녕 @Ursus, 귀하의 답변을 주셔서 감사합니다, 내 오류는 다음과 같습니다 번호 정의되지 않은 메서드'이름은 '<작업 : 0x007f83471b2818> 내가 내 게시물 –

답변

1

난 당신이 작업 개체의 속성에 액세스하려고 가정합니다. 타스크 오브젝트는 스태프 오브젝트의 중첩 된 속성입니다. 이 액세스하려면 다음과 같이 staff에서 task에 액세스 할 수 accepts_nested_attributes_for를 사용해야합니다 :

class Staff < ActiveRecord::Base 
    has_many :tasks 
    accepts_nested_attributes_for :tasks, :allow_destroy => true 
end 

class Task < ActiveRecord::Base 
    belongs_to :staff 
end 

편집 : 이제 당신이 분명히 staff 클래스 staffs_taskthrough 관계가 있음을 나는 accepts_nested_attributes_for 것을 생각하게되었는지 관계는 다음과 같이 :staffs_task이어야합니다.

class Staff < ActiveRecord::Base 
    has_many :staffs_task 
    has_many :tasks, through: :staffs_task 
    accepts_nested_attributes_for :staffs_task, :allow_destroy => true 
    accepts_nested_attributes_for :tasks, :allow_destroy => true 
end 
+0

에 모델 직원을 추가 안녕하세요 @Dawcars, 답변에 대한 감사의 것입니다 그 Task는 Ranch 모델의 중첩 된 형태입니다. 그러나 이상한 일은 내가 작업의 ID를 호출 할 수 있지만 다른 변수는 호출 할 수 없다는 것입니다. 직원 컨트롤러에 set_ranch 또는 set_task를 정의해야합니까? –

+0

위의 수정 사항을 참조하십시오. – Dawcars