Rails为belongs_to和has_many设置了多个主键的基于角色的关系

时间:2014-03-19 03:23:43

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

我的所有物品 - >用户关系有效;但是,如何在我的用户模型中设置相应的关系(有很多用户 - >项目)?

#item.rb
belongs_to :update_user, foreign_key: :item_updated_at_user_id, class_name: "User"
belongs_to :delete_user, foreign_key: :item_deleted_at_user_id, class_name: "User"

#user.rb
has_many :update_items, class_name: "Items", inverse_of: :update_user
has_many :delete_items, class_name: "Items", inverse_of: :delete_user

1 个答案:

答案 0 :(得分:2)

协会应如下所示:

class Item < ActiveRecord::Base
  belongs_to :update_user, foreign_key: :item_updated_at_user_id, class_name: "User", inverse_of: :update_items
  belongs_to :delete_user, foreign_key: :item_deleted_at_user_id, class_name: "User", inverse_of: :delete_items
end

class User < ActiveRecord::Base
  has_many :update_items, foreign_key: :item_updated_at_user_id, class_name: "Item", inverse_of: :update_user
  has_many :delete_items, foreign_key: :item_deleted_at_user_id, class_name: "Item", inverse_of: :delete_user
end

class_name: "Items"应为class_name: "Item"注意:模型名称为单数)

在关联的两侧指定foreign key选项。

此外,最好在关联的两边指定inverse_of选项。