[英]Rails Association working only one way
My model "Preconditions" creates relationships between records in the "Assignments" model, so that one assignment can be a pre-requisite for another assignment. 我的模型“前提条件”在“任务”模型中的记录之间创建关系,因此一个任务可以成为另一个任务的先决条件。
In the console, Assignment.find(3).preassigns outputs the second record from the Assignment table, as I expect. 在控制台中,Assignment.find(3).preassigns如我期望的那样从Assignment表中输出第二条记录。 However, the inverse is not working.
但是,反函数不起作用。 Assignment.find(2).mainassigns returns an empty set.
Assignment.find(2).mainassigns返回一个空集。
precondition.rb precondition.rb
class Precondition < ApplicationRecord
belongs_to :mainassign, class_name: "Assignment"
belongs_to :preassign, class_name: "Assignment"
end
assignment.rb Assignment.rb
class Assignment < ApplicationRecord
belongs_to :seminar
has_many :scores, dependent: :destroy
has_many :preconditions, class_name: "Precondition",
foreign_key: "mainassign_id",
dependent: :destroy
has_many :mainconditions, class_name: "Precondition",
foreign_key: "preassign_id",
dependent: :destroy
has_many :preassigns, through: :preconditions, as: :mainassign, source: :preassign
has_many :mainassigns, through: :preconditions, as: :preassign, source: :mainassign
validates :name, presence: true, length: { maximum: 40 }
validates :seminar_id, presence: true
validates :possible, presence: true
validates_numericality_of :possible, only_integer: true
end
Based on similar questions, I've tried adding a polymorphic tag in the Preconditions table, like so: 基于类似的问题,我尝试在前提条件表中添加一个多态标记,如下所示:
belongs_to :mainassign, class_name: "Assignment", polymorphic: true
This caused an error, but the log suggested that I try a source_type, so I tried adding that to the assignments model, like so: 这引起了一个错误,但是日志建议我尝试使用source_type,因此我尝试将其添加到分配模型中,如下所示:
has_many :mainassigns, through: :preconditions, as: :preassign, source: :mainassign, source_type: "Assignment"
But that resulted in an SQL column not found error. 但这导致未找到SQL列错误。
Thank you in advance for any insight. 预先感谢您的任何见解。
No need for polymorphic here. 这里不需要多态。 You need to change
:through
value for mainassigns
: 您需要
:through
: mainassigns
值mainassigns
:
From: 从:
has_many :mainassigns, through: :preconditions, as: :preassign, source: :mainassign
To: 至:
has_many :mainassigns, through: :mainconditions, as: :preassign, source: :mainassign
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.