Rails 中具有两种不同关系的两个资源
我是 Rails 新手,遇到了一种我无法完全理解的情况。
假设我有两个资源:用户和小部件。
用户可以使用小部件,但小部件也是用户创建的,并且应该由创建它们的用户拥有。需要有一个用户使用小部件,并且有一个用户拥有小部件。以下是我正在寻找的吗?
Class User < ActiveRecord::Base
has_many :uses
has_many :widgets, :through => :uses
has_many :owns
has_many :widgets, :through => :owns
end
Class Widget < ActiveRecord::Base
has_one :own
has_many :uses
has_many :users, :through => :uses
end
Class Use < ActiveRecord::Base
belongs_to :user
belongs_to :widget
end
Class Own < ActiveRecord::Base
belongs_to :user
belongs_to :widget
end
I am new to rails, and have a situation that I can't quite get my head around.
Lets say I have two resources, users and widgets.
Users can use widgets, but widgets are also user created, and should be owned by the user that created them. There needs to be a user uses widget, and a user owns widget. Is the following what I am looking for?
Class User < ActiveRecord::Base
has_many :uses
has_many :widgets, :through => :uses
has_many :owns
has_many :widgets, :through => :owns
end
Class Widget < ActiveRecord::Base
has_one :own
has_many :uses
has_many :users, :through => :uses
end
Class Use < ActiveRecord::Base
belongs_to :user
belongs_to :widget
end
Class Own < ActiveRecord::Base
belongs_to :user
belongs_to :widget
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我会做稍微不同的事情。
我稍微更改了名称,
widget
上存在名称冲突,不能有两个具有相同名称的关联。我还删除了 has_one 并仅设置了一个owner
,它将具有owner_id
的外键,并将类设置为User
。除此之外,您很好地设置了多对多关系。I would do it slightly different.
I changed the names a bit, you had a name conflict on
widget
, you cannot have two associations with the same name. I also removed the has_one and just set anowner
which will have a foreign_key ofowner_id
with the class set toUser
. Other than that, you set the many-to-many relationship up nicely.