管理 Rails ActiveRecord 关联的正确方法是什么?
我是 Rails 新手,所以请耐心等待……
我正在尝试创建一组与 2 个不同模型相关的数据。我目前有以下模型:
class M < ActiveRecord::Base
belongs_to :u
belongs_to :s
end
class U < ActiveRecord::Base
has_many :m
has_many :s, :through => m:
end
class S < ActiveRecord::Base
has_many :m
has_many :u, :through => m;
end
在系统中,用户可以创建许多Us和Ss。但在创建 M 时,应确保存在对“u”和“s”的引用。
我知道我可以执行以下操作:
m1 = M.create()
u1.ms << m1
s1.ms << m1
哪个有所有适当的参考,有更好的方法吗?
I am new to Rails so bear with me…
I am trying to create a set of data related to 2 different models. I currently have the following models:
class M < ActiveRecord::Base
belongs_to :u
belongs_to :s
end
class U < ActiveRecord::Base
has_many :m
has_many :s, :through => m:
end
class S < ActiveRecord::Base
has_many :m
has_many :u, :through => m;
end
In the system, the user can create many Us and Ss. But when creating an M it should make sure that there exist a reference to an "u" and an "s".
I know i can do the following:
m1 = M.create()
u1.ms << m1
s1.ms << m1
Which has all the appropriate reference, is there a better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该能够执行
one_u.s = one_s
或one_s.u = one_u
。根据 Rails 指南,新的
M 模型将由 ActiveRecord 管理。您只需像常见的
has_many
关联一样设置属性,M
行将随之创建(和删除)。You should be able to do either
one_u.s = one_s
orone_s.u = one_u
.According to the Rails Guides, new
M
models will be managed byActiveRecord
. You can just set the attribute like a commonhas_many
association, and theM
rows will be created (and deleted) along with it.