动作仅更新最后一个对象

时间:2014-07-01 06:57:57

标签: ruby-on-rails ruby ruby-on-rails-4

从最近两天开始,我试着期待在我的应用中发生什么。这是我的问题:

我的模特:

class User
has_many :orders
---
class Order
belongs_to :user
has_and_belongs_to_many :contributors, class_name: 'User'

情况: 用户可以创建订单,此订单的下一个可以添加贡献者(其他用户)与
     <%= collection_check_boxes(:order, :contributor_ids, @prac, :id, :to_s) %>

之后在OrdersController中的自定义操作中,我有类似这样的内容:

@order.contributors.each do |u|
u.orders << @order
end

这里我想将此订单添加到贡献者(用户)订单列表中。不幸的是,这只适用于最后的贡献者(用户)。从我的控制台下面记录:

    Started PATCH "/orders/282/zatwierdz" for 127.0.0.1 at 2014-07-01 08:48:59 +0200

Processing by OrdersController#zatwierdz as HTML
  Parameters: {"authenticity_token"=>"hxWUnazKLoS9t8bVmOAMeIxdo/KYuO33bUeuQZYgeV
k=", "id"=>"282"}
  User Load (0.0ms)  SELECT  "users".* FROM "users"  WHERE "users"."id" = 32  OR
DER BY "users"."id" ASC LIMIT 1
  Role Load (0.0ms)  SELECT  "roles".* FROM "roles"  WHERE "roles"."id" = ? LIMI
T 1  [["id", 4]]
  Order Load (0.0ms)  SELECT  "orders".* FROM "orders"  WHERE "orders"."id" = ?
 ORDER BY created_at DESC LIMIT 1  [["id", 282]]
  OrderItem Exists (0.0ms)  SELECT  1 AS one FROM "order_items"  WHERE "order_it
ems"."order_id" = ? LIMIT 1  [["order_id", 282]]
   (0.0ms)  begin transaction
  SQL (0.0ms)  UPDATE "orders" SET "status" = ?, "updated_at" = ? WHERE "orders"
."id" = 282  [["status", 1], ["updated_at", "2014-07-01 06:48:59.486472"]]
   (62.5ms)  commit transaction
  User Load (0.0ms)  SELECT "users".* FROM "users" INNER JOIN "orders_users" ON
"users"."id" = "orders_users"."user_id" WHERE "orders_users"."order_id" = ?  [["
order_id", 282]]
   (0.0ms)  begin transaction
   (0.0ms)  commit transaction
   (0.0ms)  begin transaction
  SQL (0.0ms)  UPDATE "orders" SET "updated_at" = ?, "user_id" = ? WHERE "orders
"."id" = 282  [["updated_at", "2014-07-01 06:48:59.564595"], ["user_id", 33]]
   (78.1ms)  commit transaction
   (0.0ms)  begin transaction
  SQL (0.0ms)  UPDATE "orders" SET "updated_at" = ?, "user_id" = ? WHERE "orders
"."id" = 282  [["updated_at", "2014-07-01 06:48:59.642719"], ["user_id", 35]]
   (78.1ms)  commit transaction
   (0.0ms)  begin transaction
  SQL (0.0ms)  UPDATE "orders" SET "updated_at" = ?, "user_id" = ? WHERE "orders
"."id" = 282  [["updated_at", "2014-07-01 06:48:59.720842"], ["user_id", 36]]
   (109.4ms)  commit transaction
   (0.0ms)  begin transaction
  SQL (0.0ms)  UPDATE "orders" SET "updated_at" = ?, "user_id" = ? WHERE "orders
"."id" = 282  [["updated_at", "2014-07-01 06:48:59.830215"], ["user_id", 37]]
   (78.1ms)  commit transaction
Redirected to http://localhost:3000/orders/282
Completed 302 Found in 437ms (ActiveRecord: 406.2ms)

我尝试将此操作与回调和模型方法一起使用但没有任何反应。也许更好的这个aprouch是使用其他协会? Anny sugestions欢迎。 求助。

1 个答案:

答案 0 :(得分:0)

通过做:

@order.contributors.each do |u|
  u.orders << @order
end

您正在将订单添加到user.orders关系,您将其定义为多个(订单)到一个(用户)。 User类上的“has_many”订单只是Order类上“belongs_to”用户的另一面。所以是的,根据您的模型,订单只有一个用户。

现在,如果您希望能够从用户端导航has_and_belongs_to_many关系,则需要define it there too