简体   繁体   English

可以使用Rails Active Record查询接口编写原始SQL吗? 应该是吗

[英]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. 在我的Rails 4应用程序中,我使用以下SQL'OR'语句对我的模型之一进行了非常简单的搜索。 It works fine. 工作正常。 Is there any way (and reason) to achieve this without raw SQL using the Rails Active Record Query Interface? 有没有任何方法(和理由)可以使用Rails Active Record查询接口在没有原始SQL的情况下实现这一目标?

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. 您可以在这里使用Arel Many rails queries use Arel behind the scenes, but you can hook into it directly. 许多rails查询在后台使用Arel,但是您可以直接将其关联。

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. 我们通常使用Arel,以便如果我们更改RDBM,它将为我们转换SQL。 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)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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