gpt4 book ai didi

ruby-on-rails - 我可以访问集合吗?在 ruby​​ on rails 中调用了一个实例方法

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

我正致力于在 ruby​​ on rails 应用程序中实现搜索表单。一般的想法是使用 form_tag 将搜索字段(通过参数)提交到我要搜索的类模型中的搜索功能。然后,搜索函数将遍历每个参数,如果函数名称出现在参数中,则执行作用域函数。

问题是,当我像这样对集合调用搜索时:

@calendar.reservations.search({:search_email => "test"})

我不知道如何从搜索功能中引用@calendar.reservations 的集合。

此外,我对为什么 @calendar.reservations.search(...) 有效感到困惑,但 Reservations.all.search 给我一个错误,说你不能在数组上调用实例方法。

我在这里获得了搜索方法的详细信息:https://gist.github.com/783964

如有任何帮助,我们将不胜感激!

最佳答案

I don't know how to refer to the collection of @calendar.reservations from within the search function.

如果您在类方法中使用self(或Reservation,它们是同一个对象),您将访问当前范围内的记录,因此在您的情况下您将仅查看特定日历的预订。

[edit] 我看了你的搜索功能,我想你想要的是:

def self.search(search_fields)  
search_fields.inject(self) do |scope, (key, value)|
scope.send(key, value)
end
end

Additionally I'm confused as to why @calendar.reservations.search(...) works, but Reservations.all.search gives me an error saying you can't call an instance method on an array.

@calendar.reservations 不返回标准数组而是(惰性)AssociationCollection ,您仍然可以在其中应用范围(和类方法作为您的 filter)。另一方面,Reservation.all 返回一个普通数组,因此您不能在那里(或任何范围)执行 search

关于ruby-on-rails - 我可以访问集合吗?在 ruby​​ on rails 中调用了一个实例方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4725174/

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