我有以下模型:
class Institute < ActiveRecord::Base
has_and_belongs_to_many :users
end
class User < ActiveRecord::Base
has_and_belongs_to_many :institutes
end
我有一个联接表“ institutes_user”。使用Rails控制台,当我创建一个属于特定研究所的新用户(假设它已经存在)时,如何自动填充该表?
当我从Rails控制台使用“ create”方法创建一个User(并传递Institute_id)时,它不会填充联接表。
谢谢!
您可以使用“铲子”运算符。例如,
Institute.first.users << User.new(first_name: "A", last_name: "B", email: "C")
将User
在users
表上插入新记录,并在表上插入新的联接行institute_users
。
您可以has_and_belongs_to_many
在此处看到添加到您的类中的其他方法的列表。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句