Rails 中具有两种不同关系的两个资源

发布于 2024-09-09 17:54:50 字数 598 浏览 8 评论 0原文

我是 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

网白 2024-09-16 17:54:50

我会做稍微不同的事情。

Class User < ActiveRecord::Base
  has_many :uses
  has_many :widgets, :through => :uses
  has_many :owned_widgets, :class_name => "Widget"
end

Class Widget < ActiveRecord::Base
  belongs_to :owner, :class_name => "User"
  has_many :uses
  has_many :users, :through => :uses
end

Class Use < ActiveRecord::Base
  belongs_to :user
  belongs_to :widget
end

我稍微更改了名称,widget 上存在名称冲突,不能有两个具有相同名称的关联。我还删除了 has_one 并仅设置了一个 owner,它将具有 owner_id 的外键,并将类设置为 User。除此之外,您很好地设置了多对多关系。

I would do it slightly different.

Class User < ActiveRecord::Base
  has_many :uses
  has_many :widgets, :through => :uses
  has_many :owned_widgets, :class_name => "Widget"
end

Class Widget < ActiveRecord::Base
  belongs_to :owner, :class_name => "User"
  has_many :uses
  has_many :users, :through => :uses
end

Class Use < ActiveRecord::Base
  belongs_to :user
  belongs_to :widget
end

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 an owner which will have a foreign_key of owner_id with the class set to User. Other than that, you set the many-to-many relationship up nicely.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文