2017-01-20 11 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

エラーを追加できますか?スタッフモデルを追加することもできます。 – Ursus

+0

こんにちは@Ursus、あなたの答えのおかげで、私の誤差がある:#用 未定義のメソッド 'name」は、<タスク: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

関連する問題