0

在给定的情况下,用户可以:

  • 邀请许多受邀者(has_many :invitations)
  • 接受一份邀请(has_one :invitation)

根据http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association has_many :through关联应该允许我使用类似于以下功能测试中的快捷方式。

但是,它失败并出现注释中指出的错误。

功能测试的片段:

assert_difference('Invitation.count') do # WORKS
  post :create, :user => { :email => invitee_email, :password => "1password" }
end

@invitee = User.find_by_email(invitee_email)
@invitation = Invitation.find_by_issuer_id_and_invitee_id(@issuer.id, @invitee.id)
assert @invitation.valid? # WORKS
assert_present @invitation.issuer # WORKS
assert_present @invitation.invitee # WORKS

# TODO: repair
assert_present @issuer.invitees # FAILS with "[] is blank"
assert_present @invitee.issuer # FAILS with "nil is blank"

来自被测方法的片段:

@issuer.create_invitation(:invitee => @invitee, :accepted_at => Time.now)
# tested as well - also fails the test:
# Invitation.create!(:issuer => @issuer, :invitee => @invitee, :accepted_at => Time.now)

邀请的相关部分.rb:

belongs_to :issuer, :class_name => "User"
belongs_to :invitee, :class_name => "User"

validates_presence_of :issuer
validates_presence_of :invitee

user.rb 的相关部分:

has_many :invitations, :foreign_key => 'invitee_id', :dependent => :destroy
has_many :invitees, :through => :invitations
has_one :invitation, :foreign_key => 'issuer_id', :dependent => :destroy
has_one :issuer, :through => :invitation

现在我想知道:

  • 什么是正确的“捷径”?
  • 我的模型首先设置正确吗?
4

1 回答 1

0

I guess you're trying to design the logic like this: User 1 can invite user 2, user 3, then the data is:

issuer_id, invitee_id
1,         2
1,         3

Suppose user 2 accepted the invitation, the data become:

issuer_id, invitee_id
1,         2
1,         3
2,         1

What if user 2 invites user 1 later? If my guess is right, your design wouldn't work.

I think you also have some misunderstanding about the associations. has_many :invitations, :foreign_key => 'invitee_id' means a user, as an invitee, received many invitations. And has_one :invitation, :foreign_key => 'issuer_id' means a user, as an issuer, sent an invitation.

于 2012-03-13T00:37:29.470 回答