gpt4 book ai didi

ruby-on-rails - 如何在 Rails 中编写作用域?

转载 作者:太空宇宙 更新时间:2023-11-03 18:08:41 24 4
gpt4 key购买 nike

我正在尝试学习如何在 Rails 中编写范围。

我有针对用户、组织和组织请求的模型。这些协会是:

User
has_one :organisation

Organisation
belongs_to :owner, class_name: 'User'
has_many :organisation_requests

Organisation_request
belongs_to :organisation

在我的组织请求模型中,我试图编写一个范围来挑选出属于组织所有者的所有组织请求。

scope :same_org, where(:organisation_id => owner.organisation_id)

然后在我的 organization_requests Controller 中,我有:

def index
@organisation_requests = OrganisationRequest.same_org
end

我试过上面的方法。所有者是用户的别名。在每个组织中,指定一名用户作为该组织的所有者。我希望该用户看到针对该所有者组织的组织请求的索引。

谁能看出我在这里做错了什么?我不太了解如何编写范围。

最佳答案

在你的模型中,试试这个:

scope :same_org, -> {where(:organisation_id => owner.organisation_id) }

关于ruby-on-rails - 如何在 Rails 中编写作用域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38648210/

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