哈希中的运算符不相等?

时间:2014-06-25 15:13:54

标签: ruby-on-rails ruby ruby-on-rails-3

将以下用户条件设置为不相等的正确语法是什么?

@instance = Comment.all(:joins => :user, :conditions => { :users => { :status => 'unpaid' } })

换句话说,我试图完成这样的事情,但显然语法不起作用。

@instance = Comment.all(:joins => :user, :conditions => { :users => { :status != 'unpaid' } })  

非常感谢!

3 个答案:

答案 0 :(得分:1)

Comment.joins(:user).where("users.status != 'unpaid' or users.status is null")

在这种情况下,您将获得状态未付或没有任何状态的所有用户。此查询生成sql如下:

SELECT "comments".* FROM "comments" INNER JOIN "users" ON "comments"."user_id" = "users"."id" WHERE ("user.status != 'unpaid' or user.status is null")

答案 1 :(得分:1)

您也可以这样做

Comment.joins(:user).where("status != ? or status is null",'unpaid')

答案 2 :(得分:0)

你必须编写一小段SQL来实现这一目标。试试这个:

Comment.joins(:user).where("users.status != 'unpaid'")

生成:

>  Comment.joins(:user).where("users.status != 'unpaid'").to_sql
SELECT "comments".* FROM "comments" INNER JOIN "users" ON "users"."id" = "comments"."user_id" WHERE (users.status != 'unpaid')

要包含nil或空状态的结果:

Comment.joins(:user).where("users.status != 'unpaid'").where("user.status" => "").where("user.status" => nil)