显示连接表中的元素

时间:2017-01-20 19:40:24

标签: ruby-on-rails ruby

我面临一个奇怪的问题;我正在尝试显示与工作人员相关的所有任务,并且有一个我不理解的错误:

  • 我只能访问任务的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

1 个答案:

答案 0 :(得分:1)

我假设您正在尝试访问任务对象的属性。任务对象是staff对象的嵌套属性。要访问此内容,您需要使用accepts_nested_attributes_fortask访问staff,如下所示:

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类与through的关系staffs_task,我认为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