ActiveRecord 根据列表中具有值的关联记录进行条件查找
使用以下 Rails 模型:
class Group < ActiveRecord::Base
has_many :group_locations, :dependent => :restrict
has_many :locations, :through => :group_locations, :dependent => :restrict
end
class Location < ActiveRecord::Base
has_many :group_locations, :dependent => :destroy
has_many :groups, :through => :group_locations
end
class GroupLocation < ActiveRecord::Base
belongs_to :group
belongs_to :location
end
我试图查找与字符串“group_list”中包含的多个组中的至少一个相关联的所有位置(例如“1 ,2,3,4,5")。如果它是位置记录中的字段,我将指定“*field in (#{group_list})*”条件。但是,当我想要至少拥有一个其“group_id”在列表中的位置的“group_location”(或者,一个其 group_id 在列表中的“组”)时,我该如何实现我的目标。
我知道如何用纯 SQL 做到这一点,但是如何用 Rails 做到这一点?
With the following Rails models:
class Group < ActiveRecord::Base
has_many :group_locations, :dependent => :restrict
has_many :locations, :through => :group_locations, :dependent => :restrict
end
class Location < ActiveRecord::Base
has_many :group_locations, :dependent => :destroy
has_many :groups, :through => :group_locations
end
class GroupLocation < ActiveRecord::Base
belongs_to :group
belongs_to :location
end
I am trying to Find all of the locations that are associated with at least one of several groups contained in the string "group_list" (e.g. "1,2,3,4,5"). If it was a field from the Location record, I would specify a condition of "*field in (#{group_list})*". But how do I accomplish my goal when I want to have at least one of the location's "group_location" whose "group_id" is in the list (or, alternatively, one "group" whose group_id is in the list).
I know how to do it with pure SQL, but how do you do it with Rails?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
@太郎你是对的。首先添加代码
然后我继续定义一个范围只是为了使其成为一个漂亮的包:
感谢您的帮助。
@taro You are right. Started by adding the code
Then I proceeded to define a scope just to make it a nice package:
Thanks for your help.