为什么这个Rails关联快捷方式失败?什么是正确的方法?

时间:2012-03-12 21:49:12

标签: ruby-on-rails associations has-many-through functional-testing has-one

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

  • 邀请了许多被邀请者(has_many:邀请)
  • 接受一个邀请(has_one:邀请)

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

但是,它会因评论中注明的错误而失败。

来自功能测试的

片段:

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

现在我想知道:

  • 什么是正确的“快捷方式”?
  • 我的模型首先设置正确吗?

0 个答案:

没有答案