简体   繁体   English

与用户的自我加入关联

[英]Self-join association with users

I have models: User has_many :orders end; 我有一些模型:用户has_many:orders end; Order belongs_to :user end; 订单belongs_to:用户端;

This associations work very well but now i want that User who create order could add another Users for this order. 这种关联非常有效,但是现在我希望创建订单的用户可以为此订单添加其他用户。

Edit: 编辑:

In my orders/show.html.erb i have something like this 在我的订单/ show.html.erb中,我有这样的东西

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

<% end %> I know this is wrong because i choose here id user who create order, but in this situation i have problem with define correct associations probably this is good idea? <%end%>我知道这是错误的,因为我在这里选择创建订单的id用户,但是在这种情况下,我在定义正确的关联时遇到问题,这可能是个好主意吗? => =>

order has_many :workes, class_name: 'User'

How can i achieve this functionality? 我如何实现此功能?

You can have several relations to the same class, but you probably want to differentiate them (the other Users of your order are probably not the owner). 您可以对同一个类有多个关系,但是您可能希望区分它们(订单的其他用户可能不是所有者)。 Something like: 就像是:

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

This will create a one to many relation between the order and a list of Users known as "contributors": 这将在订单和称为“参与者”的用户列表之间建立一对多关系:

owner = order.user # the initial user
contributors = order.contributors # a list of users related to this order.

You are looking for has_and_belongs_to_many association: 您正在寻找has_and_belongs_to_many关联:

Create join table 'orders_users' 创建联接表“ orders_users”

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

Add association: 添加关联:

class Order < ActiveRecord::Base
  belongs_to :user
  has_and_belongs_to_many :contributors, class_name: 'User'
end

And all should work. 所有应该工作。

Join 加入

You'll need to add another cog into the system - with has_many :through or has_and_belongs_to_many join tables 您需要在系统中添加另一个齿轮-使用has_many :throughhas_and_belongs_to_many连接表

As Martin mentioned, you'll need to do something like this: 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

This will allow you to set as many users per order as you need - allowing you to call: 这将允许您根据需要为每个order设置尽可能多的users -允许您致电:

@user = User.first
@user.orders


@order = Order.first
@order.users

-- -

Just noticed this is not self-join . 只是注意到这不是self-join I can refactor if you'd like it to be self-referential 如果您希望它具有自我参照性,我可以重构

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM