给定以下模型
class Team < ActiveRecord::Base
has_many :memberships, class_name: "TeamMembership"
has_many :members, -> { uniq(true) }, source: :user, through: :memberships
has_many :owners, -> { where('team_memberships.owner' => true) }, source: :user, through: :memberships
end
这很好用(奇怪uniq
的语法是因为我在 Rails 4 上),但是在我的规范中:
describe Team do
describe "users and owners" do
fixtures :users
subject { create :team }
let(:bob) { users :bob }
let(:alice) { users :alice }
it "doesn't allow a member to be added more than once" do
subject.members << bob
subject.members.should include(bob)
subject.members << bob
subject.members.count.should == 1
end
it "doesn't allow an owner to be added more than once" do
subject.owners << bob
subject.owners.should include(bob)
subject.owners << bob
subject.owners.count.should == 1
end
end
end
您会注意到第二个示例“它不允许多次添加所有者”,我正在检查是否bob
已正确添加到所有者列表中,但他没有。他在member
列表中,但他的TeamMembership
实例缺少owner = true
标志。
我确定我在以前的 Rails 版本中已经有这个工作,但那时它是conditions: { owner: true }
关系的一个选项,而不是一个惰性求值的 lambda。
我可以通过以下方式解决:
subject.owners << bob
subject.members.should include(bob)
subject.memberships.find_by_user_id(bob.id).update_attribute(:owner, true)
这工作得很好,但似乎还有很长的路要走。简而言之,我想要一种方法来覆盖owners<<()
模型Team
,然后从那里运行,但我不确定从哪里开始。在短期内,我的工作就足够了,但我希望做得更好。
我如何team.owners << bob
让他新创建的成员设置为team_membership.owner = true
分配?