Ruby on rails 不等于条件
我想要一个where子句,它具有相等和不相等的条件:Ruby on rails 不等于条件,ruby-on-rails,ruby-on-rails-3,Ruby On Rails,Ruby On Rails 3,我想要一个where子句,它具有相等和不相等的条件: @user = User.where(:user_id => current_user.id, :author_id != current_user.id).nil? ? (render :something) : (render :somethingelse) 上述方法不起作用: 语法错误,意外“'), 应为tASSOC…d,:用户\u id= 当前用户id)。无?(渲染 :索引):(关于 但是,如果我将第二个条件从!=更改为=>,
@user = User.where(:user_id => current_user.id, :author_id != current_user.id).nil? ? (render :something) : (render :somethingelse)
上述方法不起作用:
语法错误,意外“'),
应为tASSOC…d,:用户\u id=
当前用户id)。无?(渲染
:索引):(关于
但是,如果我将第二个条件从!=
更改为=>
,它将起作用
如何在一个where clase中同时具有这两个条件?谢谢语法错误是因为您试图使用
!=
而不是=>
。where
方法不支持带散列参数的不等式,因此需要使用数组参数来编写not equal
User.where(:user_id => current_user.id).where(['users.author_id <> ?', current_user.id])
User.where(:User\u id=>current\u User.id)。where(['users.author\u id',current\u User.id])
我认为应该是:
@user = User.where(['user_id = ? AND author_id <> ?', current_user.id, current_user.id])
render(@user ? :something : :somethingelse)
@user=user.where(['user\u id=?AND author\u id',current\u user.id,current\u user.id])
渲染(@user?:something::somethingelse)
使用散列条件只能进行相等、范围和子集检查
您需要下拉到直接SQL或反向arel查询,请参见以下内容:如何使用arel从用户id=?和作者id!=?的用户中生成查询“
select*”:
使用Arel并不像使用散列条件来处理简单条件那样简洁,但它的功能要强大得多
这里有一个链接,指向Arel提供的(eq
,not_eq
,gt
,lt
,等等)。Rails 4已经解决了这些问题
Model.where.not(:colname => nil)
#=> returns all records whose :colname values are not nil
不确定您是否知道,不相等条件通常与(author_id)NULL值不匹配。如果需要,您必须执行或author_id为NULL
@users = User.where("user_id = ? AND (author_id != ? OR author_id IS NULL)",
current_user.id, current_user.id)
render(@users.present? ? :something : :somethingelse)
还要注意,我使用的是@users.present?
,因为其中
查找程序返回一个ActiveRecord::Relation
数组。@taro我完成了“RubyonRails教程:通过示例学习Rails”本周,但它没有涵盖这些条件,所以我还在学习。它还建议我在转向Ruby之前先从Rails开始。但是谢谢你的反馈。你应该使用empty?
而不是nil?
,因为where
本身返回一个数组。谢谢道格拉斯。有没有办法使用:author\id inst我不想让它成为引号中的文字?(这并不重要,只是好奇)我唯一能补充的建议是看看meta_where,它实际上支持与你在问题中所发布的语法非常相似的语法。如果你使用Arel,你也可以使用:author_id而不是字符串(见下面我的答案)…谢谢你也这么做了。我想我不能用.nil?在一行中获得所有信息,正如我所希望的:)这个答案更好,因为它更不依赖数据库。例如,有些数据库不理解=代码>但其他人会。
@users = User.where("user_id = ? AND (author_id != ? OR author_id IS NULL)",
current_user.id, current_user.id)
render(@users.present? ? :something : :somethingelse)