如何<<具有集合属性的连接模型

时间:2014-06-18 16:50:46

标签: ruby-on-rails rspec

我有一个User模型,它通过UserRelationship连接表连接到另一个User模型。 UserRelationships具有必须设置的属性(已批准/已暂停/已撤销),但不默认为任何选项。有两个协会反映了这一点,旅行者和代表,所以我的模型看起来像这样:

User.rb
  has_many :traveler_relationships, :class_name => 'UserRelationship', :foreign_key => :delegate_id  
  has_many :travelers, :class_name => 'User', :through => :traveler_relationships

  has_many :delegate_relationships, :class_name => 'UserRelationship', :foreign_key => :user_id
  has_many :delegates, :class_name => 'User', :through => :delegate_relationships

  has_many :buddy_relationships, class_name: 'UserRelationship', foreign_key: :user_id
  has_many :buddies, class_name: 'User', through: :buddy_relationships, source: :delegate


UserRelationship.rb
  belongs_to :relationship_status
  belongs_to :traveler, :class_name => 'User', :foreign_key => 'user_id'
  belongs_to :delegate, :class_name => 'User'

  PENDING = 1
  CONFIRMED = 3
  REVOKED = 5

我正在尝试编写一些规范,其中一个用户与另一个用户相关,编写它的最简单方法是@user1.travelers << @user2但是这会使UserRelationship.relationship_status不是null的数据库约束失败。

当我尝试@user1.buddies.create(delegate: @user2, relationship_status: RelationshipStatus::CONFIRMED)时,它无法在UnknownAttributeError上说delegate。我查看this question并使用attr_acessible尝试了它的解决方案,但它没有更改UnknownAttributeError

使用属性设置创建此连接记录的方法是什么?

2 个答案:

答案 0 :(得分:0)

当您尝试从buddies创建时,您处于正确的轨道上(我假设这是您的连接模型关系)。问题是您的列名称为relationship_status,并且您将status传递给create。试试这个:

@user1.buddies.create(delegate: @user2, relationship_status: RelationshipStatus::CONFIRMED

答案 1 :(得分:0)

我认为UserRelationship有一个代表

的foreign_key delegate_id
class User < ActiveRecord::Base
  has_many :traveler_relationships, :class_name => 'UserRelationship', :foreign_key => :user_id
  has_many :delegate_relationships, :class_name => 'UserRelationship', :foreign_key => :delegate_id

  has_many :travelers, :class_name => 'User', :through => :traveler_relationships
  has_many :delegates, :class_name => 'User', :through => :delegate_relationships
end

class UserRelationship < ActiveRecord::Base
  belongs_to :traveler, :class_name => 'User', :foreign_key => :user_id
  belongs_to :delegate, :class_name => 'User', :foreign_key => :delegate_id

  PENDING = 1
  CONFIRMED = 3
  REVOKED = 5
end

我不认为您可以使用快捷方式@user1.delegates << @user2,因为您需要指定关系状态。尝试:

@user1.traveler_relationships.create(delegate: @user2, relationship_status: RelationshipStatus::CONFIRMED)

我在这里排除了好友的同义词。它很复杂。当这有效时,您可以考虑添加同义词。