gpt4 book ai didi

ruby-on-rails - 有许多通过关联扩展

转载 作者:数据小太阳 更新时间:2023-10-29 07:39:59 25 4
gpt4 key购买 nike

是否可以通过关联扩展来设置有多个?我有:

class User < ActiveRecord::Base

has_many :friendships do
def accepted
where status: "accepted"
end
def rejected
where status: "rejected"
end
end

has_many :friends, through: :friendships do
def accepted
# Something equivalent to the following using association extension:
# where("friendships.status = 'accepted'")
end
def rejected
# Something equivalent to the following using association extension:
# where("friendships.status = 'rejected'")
end
end

end

如何使用友谊协会扩展设置我的 friend 协会(通过友谊)?

最佳答案

如果您对 where 关系使用 Arel 表达式,则可以取消绑定(bind)这些方法并将它们重新绑定(bind)到 friends 关联:

class User < ActiveRecord::Base
has_many :friendships do
def accepted
where(Friendship.arel_table[:status].eq('accepted'))
end
def rejected
where(Friendship.arel_table[:status].eq('rejected'))
end
end

has_many :friends, through: :friendships do
def accepted
proxy_association.owner.friendships.extensions.first.instance_method(:accepted).bind(self).call
end
def rejected
proxy_association.owner.friendships.extensions.first.instance_method(:rejected).bind(self).call
end
end
end

使用该代码,将正确生成 SQL,因此该测试通过:

def test_stuff
tom = User.create! name: "tom"
fred = Friend.create! name: "fred"
jerry = Friend.create! name: "jerry"
Friendship.create! user: tom, friend: fred, status: 'accepted'
Friendship.create! user: tom, friend: jerry, status: 'rejected'
tom.reload
fred.reload
assert_equal "fred", tom.friends.accepted.first.name
assert_equal "jerry", tom.friends.rejected.first.name
end

关于ruby-on-rails - 有许多通过关联扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6470057/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com