Ruby on rails 与用户的自加入关联

Ruby on rails 与用户的自加入关联,ruby-on-rails,ruby,associations,Ruby On Rails,Ruby,Associations,我有模型: 用户有多个:订单结束; 订单所属对象:用户端 这种关联非常有效,但现在我希望创建订单的用户可以为该订单添加其他用户 编辑: 在我的订单/show.html.erb中,我有类似的内容 <%= form_for @order do |f| %> <td> <%= f.select :user_id, @prac %> </td> 如何实现此功能?您可以与同一类有多个关系,但您可能希望区分它们(订单的其他用户可能不是所有者)。比如: c

我有模型: 用户有多个:订单结束; 订单所属对象:用户端

这种关联非常有效,但现在我希望创建订单的用户可以为该订单添加其他用户

编辑:

在我的订单/show.html.erb中,我有类似的内容

<%= form_for @order do |f| %>
<td>
  <%= f.select :user_id, @prac %>
</td>

如何实现此功能?

您可以与同一类有多个关系,但您可能希望区分它们(订单的其他用户可能不是所有者)。比如:

class Order < ActiveRecord::Base
  belongs_to: user
  has_many: contributors, , class_name: 'User' # need to specify else Rails will look for a "Contributor" class
end

您正在查找的
具有且属于多个
关联:

class Order < ActiveRecord::Base
  belongs_to :user
  has_and_belongs_to_many :contributors, class_name: 'User'
end
创建联接表“订单\用户”

create_table :contributors_orders, :id => false do |t|
  t.integer :contributor_id
  t.integer :user_id
end
添加关联:

class Order < ActiveRecord::Base
  belongs_to :user
  has_and_belongs_to_many :contributors, class_name: 'User'
end
类顺序
所有这些都应该起作用。

加入

您将需要向系统中添加另一个cog-with或join表

正如
Martin
所述,您需要执行以下操作:

#app/models/user.rb
Class User < ActiveRecord::Base
   has_and_belongs_to_many :orders
end

#app/models/order.rb
Class Order < ActiveRecord::Base
   has_and_belongs_to_many :users
end

#orders_users table
order_id | user_id
--


刚刚注意到这不是
自连接
。我可以重构,如果您希望它是自引用的

,那么您想在用户和订单之间建立多对多关系吗?听起来像是的工作。我创建了:create_table“orders_users”,id:false,force:true do | t | t.integer“order_id”t.integer“user_id”end。有了这个,其他的工作都很好。谢谢你的帮助。
#app/models/user.rb
Class User < ActiveRecord::Base
   has_and_belongs_to_many :orders
end

#app/models/order.rb
Class Order < ActiveRecord::Base
   has_and_belongs_to_many :users
end

#orders_users table
order_id | user_id
@user = User.first
@user.orders


@order = Order.first
@order.users