【发布时间】: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