ruby-on-rails-3 – Rails:加入多个条件
发布时间:2020-12-17 04:37:57 所属栏目:百科 来源:网络整理
导读:我有一个简单的模型 class Interest ActiveRecord::Base has_and_belongs_to_many :user_profilesendclass UserProfile ActiveRecord::Base has_and_belongs_to_many :interestsend 当我想查询具有特定兴趣的所有用户时,这很简单 UserProfile.joins(:interes
我有一个简单的模型
class Interest < ActiveRecord::Base has_and_belongs_to_many :user_profiles end class UserProfile < ActiveRecord::Base has_and_belongs_to_many :interests end 当我想查询具有特定兴趣的所有用户时,这很简单 UserProfile.joins(:interests).where('interests.id = ?',an_interest) 但是,我如何找到有多种兴趣的用户?当然,如果我这样做 UserProfile.joins(:interests).where('interests.id = ?',an_interest).where('interests.id = ?',another_interest) 我总是得到一个空结果,因为在连接之后,没有行可以同时具有interest.id = an_interest和interest.id = another_interest. ActiveRecord中有没有办法表达“我想要有2个(指定)兴趣的用户列表? 更新(解决方案)这是我提出的第一个工作版本,对Omar Qureshi赞不绝口 specified_interests.each_with_index do |i,idx| main_join_clause = "interests_#{idx}.user_profile_id = user_profiles.id" join_clause = sanitize_sql_array ["inner join interests_user_profiles interests_#{idx} on (#{main_join_clause} and interests_#{idx}.interest_id = ?)",i] relation = relation.joins(join_clause) end 解决方法
in(?)并不好 – 它是一个OR表达式
您需要做的是将多个连接写出来 profiles = UserProfile interest_ids.each_with_index do |i,idx| main_join_clause = "interests_#{idx}.user_profile_id = user_profiles.id" join_clause = sanitize_sql_array ["inner join interests interests_#{idx} on (#{main_join_clause} and interests_#{idx}.id = ?)",i] profiles = profiles.join(join_clause) end profiles 您可能需要更改main_join_clause以满足您的需求. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- ruby-on-rails – 如何根据其他属性值添加自定义验证消息?
- PostgreSQL学习手册(索引)
- IBM Rational Functional Tester V8.1新增功能简介
- objective-c – 基于View的NSTableView等效于tableView:wi
- 什么是Oracle PL / SQL COALESCE函数的C#等价物?
- ruby-on-rails – Ruby on Rails路由:具有更多参数的命名空
- 修改MetaBase.xml后不能保存的两种解决方
- 第5章 会修电脑不会修收音机?——依赖倒转原则 大话设计模
- Swiftで作るToDoアプリ開発チュートリアル
- Animation动画详解(十)——联合动画的XML实现与使用示例