简体   繁体   中英

Can this raw SQL be written using the Rails Active Record Query Interface? Should it be?

In my Rails 4 app I make a fairly simple search for one of my models using the following SQL 'OR' statements. It works fine. Is there any way (and reason) to achieve this without raw SQL using the Rails Active Record Query Interface?

Activity.where("
    user_id = ? OR 
    category = ? OR 
    (secondary_id = ? AND secondary_model = ?) OR 
    (tertiary_id = ? AND tertiary_model = ?)",
    user_id, "Announcement", user_id, "user", user_id, "user"
).uniq

You could use Arel here. Many rails queries use Arel behind the scenes, but you can hook into it directly.

As to whether you should, I think it would depend on the project. We use Arel generally so that if we ever change our RDBM, it will take care of converting the SQL for us. I don't think it really makes it look much better.

Your code would look something like this

activities = Activity.arel_table
activities
   .where(activities[:user_id].eq(user_id)
   .or(activities[:category].eq("Announcement")
   .or((activities[:secondary_id].eq("user").and(activities[:secondary_model].eq(user_id))
   .or((activities[:tertiary_id].eq("user").and(activities[:secondary_model].eq(user_id)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM