Rails调用同一表中的不同字段

时间:2019-03-08 19:14:37

标签: mysql ruby-on-rails ruby

我想在同一张表中调用不同的字段,

分配者!=打开者

我无法呼叫分配了主题的用户

mysql users table

mysql issues table

show.html.erb screenshot

<p>
  <strong>Assignedby:</strong>
  <%= @issue.user.try(:fullname) %>

</p>

<p>
  <strong>Openedby:</strong>
 <%= @issue.user.try(:fullname) %>

</p>

class Issue < ApplicationRecord

  belongs_to :project, foreign_key: :project_id, optional: true

  belongs_to :user, foreign_key: :assignedby_id, optional: true

  belongs_to :user, foreign_key: :openedby_id, optional: true

  belongs_to :user, foreign_key: :closedby_id, optional: true

end

1 个答案:

答案 0 :(得分:1)

您不能为所有这些belongs_to关联赋予相同的名称,它们需要不同,例如:

class Issue < ApplicationRecord
  with_option optional: true do
    belongs_to :project
    belongs_to :assigner, class_name: 'User', foreign_key: :assignedby_id
    belongs_to :creator,  class_name: 'User', foreign_key: :openedby_id
    belongs_to :closer,   class_name: 'User', foreign_key: :closedby_id
  end
end