【问题标题】:How do I write a scope in Rails?如何在 Rails 中编写范围?
【发布时间】:2016-07-28 23:16:42
【问题描述】:

我正在尝试学习如何在 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 控制器中,我有:

def index
    @organisation_requests = OrganisationRequest.same_org
end

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

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

【问题讨论】:

  • 嘿,这个问题你解决了吗?
  • 嗨@AndreyDeineko - 我仍在努力解决它。我还有另一个问题阻止我调用范围 - 所以我先解决这个问题。我有你的笔记,如果我能正常工作,我会更新以接受你的答案。感谢您的跟进。我学的很慢……
  • 嘿,祝你好运!我们都已经开始一段时间了;)

标签: ruby-on-rails ruby scope


【解决方案1】:

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

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

【讨论】:

  • 错了。您如何期望所有者在关系中拥有organisation_id,其中organisation belongs_to 所有者?
【解决方案2】:

赞成的答案是错误的(不是个人的,@Hasmukh Rathod) - users 表中没有 organisation_id 列(实际上反之亦然 - 有一个 user_idorganisations 表)。

我会建议以下解决方案:

scope :same_org, ->(owner_id) { joins(organisation: :user).where(users: { id: owner_id }) }

拥有上述范围,您需要做的是将owner_id 作为参数传递。我确信有一种方法可以在不将参数传递给范围的情况下使其工作,但我还不确定如何(我刚刚醒来:D)。

例如:

owner_id = User.find(1).id
OrganisationRequest.same_org(owner_id) # would give you the expected collection of requests

【讨论】:

    猜你喜欢
    • 2017-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多