【问题标题】:Rails: has_many through between two models and also a has_many/belongs to on the same modelsRails: has_many through 在两个模型之间,还有一个 has_many/belongs to 在相同的模型上
【发布时间】:2023-03-22 18:25:01
【问题描述】:

我有很多直通关系来定义用户已回答的问题。

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

通常你只会在用户和问题之间创建一个 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 列添加到问题表中

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

我有什么问题?

【问题讨论】:

  • 您如何尝试添加created_by_id
  • 我认为这可能是我的问题....我不知道如何添加 created_by_id...
  • created_by_id 将在创建问题时添加。所以在你的控制器中你可以尝试@question = current_user.questions_created.new(params[:question])之类的东西,然后通过@question.save保存它。或者无论您使用什么逻辑,您只需要通过user_instance.created_question_association 调用问题

标签: ruby-on-rails rails-activerecord


【解决方案1】:

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

# 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

【讨论】:

  • author_id 比 created_by_id 好得多...但“author_id”字段仍然为零
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-27
  • 1970-01-01
  • 1970-01-01
  • 2019-09-26
  • 2014-08-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多