注意:我找到了解决问题的方法。来自中国的好意。
如果您有 RailsAdmin,您可能会注意到,只要两个问题字段(assumption_question_id,consequent_question_id)的一个字段等于问题的 id,您就可以看到一个问题的所有规则。
我对此进行了详细测试,发现 Rails 总是生成一个条件“question_id = [current_id]”,它使 to_sql 输出
SELECT `rules`.* FROM `rules` WHERE `rules`.`question_id` = 170
以及以下型号的原因
class Question < ActiveRecord::Base
has_many :options
# Notice ↓
has_many :rules, ->(question) { where("assumption_question_id = ? OR consequent_question_id = ?", question.id, question.id) }, class_name: 'Rule'
# Notice ↑
end
使 Question.take.rules.to_sql 变成这样
SELECT `rules`.* FROM `rules` WHERE `rules`.`question_id` = 170 AND (assumption_question_id = 170 OR consequent_question_id = 170)
是我们还没有摆脱烦恼question_id
,所以无论我们如何正确描述或条件,我们的条件都遵循“与”。
然后,我们需要搭上它。如何?
点击这里你就知道了,找到8.1扇区,你就可以看到
Article.where(id: 10, trashed: false).unscope(where: :id)
# SELECT "articles".* FROM "articles" WHERE trashed = 0
然后让我们这样做:
class Question < ActiveRecord::Base
has_many :options
# Notice ↓
has_many :rules, ->(question) { unscope(where: :question_id).where("assumption_question_id = ? OR consequent_question_id = ?", question.id, question.id) }, class_name: 'Rule'
# Notice ↑
end
class Rule < ActiveRecord::Base
belongs_to :option
belongs_to :assumption_question, class_name: "Question", foreign_key: :assumption_question_id, inverse_of: :assumption_rules
belongs_to :consequent_question, class_name: "Question", foreign_key: :consequent_question_id, inverse_of: :consequent_rules
end
class Option < ActiveRecord::Base
belongs_to :question
has_one :rule
end
全部完成。
最后
这是我在 stackoverflow 上的第一个答案,这种方法在其他任何地方都找不到。
谢谢阅读。