How can I insert or store multiple ids in a single column in Rails?

和自甴很熟 提交于 2020-01-25 11:18:45

问题


How can I insert or save multiple ids as comma separated e.g (2,5,8,10) values in single column in database for many to many relationship? I am using active admin for resource management.


回答1:


The has_many :through Association

A has_many :through association is often used to set up a many-to-many connection with another model. This association indicates that the declaring model can be matched with zero or more instances of another model by proceeding through a third model. For example, consider a medical practice where patients make appointments to see physicians. The relevant association declarations could look like this

class Physician < ApplicationRecord
  has_many :appointments
  has_many :patients, through: :appointments
end

class Appointment < ApplicationRecord
  belongs_to :physician
  belongs_to :patient
end

class Patient < ApplicationRecord
  has_many :appointments
  has_many :physicians, through: :appointments
end


来源:https://stackoverflow.com/questions/53443147/how-can-i-insert-or-store-multiple-ids-in-a-single-column-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!