Ahmad Al-kheat Ahmad Al-kheat - 1 month ago 21
MySQL Question

How do I write this query in Rails without Arel

I want to achieve this :

where(
"(memberships.id IN (?) AND memberships.user_id == ?)
OR (memberships.user_id == ? AND communities.hidden == ?)",
m, user.id, nil, false)


This is returning an error :

ActiveRecord::StatementInvalid:
Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '= 77 OR memberships.user_id == NULL AND communities.hidden == 0)' at line 1: SELECT DISTINCT `communities`.* FROM `communities` LEFT JOIN `memberships` ON `communities`.`id` = `memberships`.`community_id` AND `memberships`.`user_id` = 77 WHERE `communities`.`deleted_at` IS NULL AND (memberships.id IN (NULL) AND memberships.user_id == 77 OR memberships.user_id == NULL AND communities.hidden == 0)


I don't want to use Arel

Answer

I think the problem is that you're using double equal sing, whereas should use single:

where("(memberships.id IN (?) AND memberships.user_id = ?) OR (memberships.user_id = ? AND communities.hidden = ?)", m, user.id, nil, false)

Other than that the query looks valid to me (I suppose you're doing some kind of JOIN (using joins() or includes() before where clause)).

Comments