【问题标题】:Need help in building associations for my scenario在为我的场景建立关联时需要帮助
【发布时间】:2014-12-25 15:28:29
【问题描述】:

我不精通联想,对这部分没有广泛的了解。

以下是我的用例:
有两种型号:

  • 员工
  • 评分

--> 员工(作为团队负责人)可以给他的团队成员(员工)评分

只取has_manyemployee to rating 之间的关系会是个好主意吗? 另外,我有点困惑,我将如何在Team Lead 登录会话中分别显示团队领导的评级及其团队成员的评级。

请帮忙。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 activerecord associations


    【解决方案1】:

    ratings 表应该有一个giver_id 和一个employee_id 列。那么:

    class Employee < ActiveRecord::Base
      has_many :given_ratings, foreign_key: :giver_id, class_name: Rating
      has_many :ratings
    end
    
    class Rating < ActiveRecord::Base
      belongs_to :giver, class_name: Employee
      belongs_to :employee
    end
    

    那么对于任何员工来说,以下应该是可行的:

    team_lead = # fetch employee however
    team_lead.ratings # ratings given TO this employee
    team_lead.given_ratings # ratings given BY this employee
    

    【讨论】:

    • 谢谢。但是我在 team_lead.given_ratings.count 上遇到了一些错误。在此处登录goo.gl/gzwSts。你能查一下吗?
    • 老兄,您需要将giver_id 列添加到您的评分中。如果它回答了您的问题,则将我的答案标记为选定的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-27
    • 1970-01-01
    • 2011-10-30
    • 1970-01-01
    • 2018-12-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多