如何在rails的one_to_many关联中访问数据?

问题描述 投票:-1回答:1

我正在使用装置来存储用户。我在project_manager和Director之间的同一user表中创建了一对多关联。与每个用户项目之间的one_to_many关联。我可以通过他们的director_id访问project_managers,但是我无法通过他们对应的Director仪表板访问project_manager的项目。这是我的代码:

user.rb

  has_many :projects
  belongs_to :director, class_name: 'User', required: false
  has_many :project_manager, foreign_key: 'director_id', class_name: 'User'

directors_controller.rb

  def index
    @director_id = current_user.id
    @users = User.where(director_id: @director_id) #able to access project_managers with same director_id

    @project = Project.all #this is for test i want to access here project_managers project of same director_id
  end

index.html.erb(导演)

<table>
  <thead>
    <tr>
      <th class="th-style">Project Name</th>
    </tr>
  </thead>

  <tbody>
    <% @projects.each do |project| %>
      <tr>
        <td><%= project.project_name %></td>
      </tr>
    <% end %>
  </tbody>
</table>
ruby-on-rails ruby-on-rails-5
1个回答
0
投票
  def index
    @director_id = current_user.id
    @users = User.where(director_id: @director_id)
    @projects = Project.where(user_id: @users)
  end
© www.soinside.com 2019 - 2024. All rights reserved.