在Rails 7中,我如何在Question模型的一个列中引用另一个模型?

huangapple go评论57阅读模式
英文:

How can I reference another model in a column of my Question model in Rails 7?

问题

在 Rails 7 中,我有一个名为 Question 的模型。这些问题可以使用下拉菜单或单选按钮进行回答。下拉菜单的信息来自其他模型。我有其他模型,比如 PlaceUnit 等。我需要在 Question 中有一列,可以以某种方式保存这些模型的引用,或者像 question_col_model = Place.all 这样。我正在尝试弄清楚如何实现,但失败了。
起初,我考虑将它们保存在数组中,因为 PostgreSQL 支持数组。但它们就像该实例的快照,我需要实时更新。当模型更新时,下拉菜单会自动更新。
在使用 @questions 进行循环时,我需要为不同的问题获取不同的模型。

英文:

In rails 7, I have a model called Question. the questions are answered using dropdowns or radio buttons. The dropdown infos come from another models. I have another models like Place, Unit etc. I need a column in the Question where I can somehow save these models referance or maybe like question_col_model = Place.all. I am trying to figure out how to do but failed.
I can not use anything but models for the dropdowns. Thank you

At first I thought of keeping them in array as postgresql supports them. But they are like snapshots of that instance, I need realtime updates. When the model updates, the dropdown updates automaticaly.
When using @questions to loop, I need to get different models for different questions.

答案1

得分: 1

你可以这样设置你的关系:

class Question < ApplicationRecord
  has_many :answers
end

class Answer < ApplicationRecord
  belongs_to :question # 所以它有一个名为 "question_id" 的字段
end

你会有多个具有相同 "question_id" 值的答案。

英文:

You set up your relationships like this:

class Question < ApplicationRecord
  has_many :answers
end

class Answer < ApplicationRecord
  belongs_to :question # so it has a field called "question_id"
end

you will have several answers with the same question_id value

huangapple
  • 本文由 发表于 2023年5月29日 04:23:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76353463.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定