gpt4 book ai didi

ruby-on-rails - rails : has_many through between two models and also a has_many/belongs to on the same models

转载 作者:行者123 更新时间:2023-12-04 06:05:45 26 4
gpt4 key购买 nike

我有一个 has many through 关系来定义用户已回答的问题。

如何为用户创建的问题建立关系?

通常你会在用户和问题之间创建一个 has_many 和 belongs_to 关系,但是因为我也在做一个 has_many 通过这将不起作用。

这是我目前所拥有的:

模型:

Users
Questions
Answered_questions

用户模型

has_many :answered_questions
has_many :questions, :through => :answered_questions

问题模型:

has_many :answered_questions
has_many :users, :through => :answered_questions

Answered_questions 模型

belongs_to :question
belongs_to :user

编辑

我找到了这个答案:https://stackoverflow.com/a/12637532/756623 ,这促使我尝试这样做:

添加用户模型:

has_many :questions_created, :class_name => "Question", :inverse_of => :created_by

问题模型添加:

belongs_to :created_by, :class_name => "User", :foreign_key => "created_by_id", :inverse_of => :questions_created 

我还将 created_by_id 列添加到 Questions 表中

现在...user_id 未添加到 created_by_id 列。

我有什么问题吗?

最佳答案

我认为这样的事情可以解决您的问题:

# User
has_many :answered_questions
has_many :questions, :through => :answered_questions
has_many :created_questions, class_name: Question, foreign_key: :author_id

# Question
has_many :answered_questions
has_many :users, :through => :answered_questions
belongs_to :author, class_name: User

# Answered questions
belongs_to :question
belongs_to :user

关于ruby-on-rails - rails : has_many through between two models and also a has_many/belongs to on the same models,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15056096/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com