Rails 4.0,使用帮助程序解析查询占位符

时间:2013-10-29 20:48:18

标签: ruby-on-rails

我想使用辅助函数,填写where子句

在我看来,我有一行

<%= f.collection_select(:artikelgroep_id, Artikelgroep.where(artikelgroeps_not_in_users_selection), :id, :omschrijving) %>

在帮手中:

module ArtikelgroepsHelper
  def artikelgroeps_not_in_users_selection
    a1='"id NOT IN (SELECT artikelgroep_id FROM user_artikelgroeps WHERE user_id = :uid)"'  + "," +  "{uid: @user.id}"
 end
end

当我执行视图时,我收到消息:

SELECT `artikelgroeps`.* FROM `artikelgroeps`  WHERE ("id NOT IN (SELECT artikelgroep_id FROM user_artikelgroeps WHERE user_id = :uid)",{uid: @user.id})

看起来占位符没有得到解决。

当我直接填写助手的结果而不是artikelgroeps_not_in_users_selection时,它工作正常。

如何强制解析占位符??

2 个答案:

答案 0 :(得分:1)

执行此操作是错误的方法(改为使用范围),但要使其工作,您需要从方法返回一组参数,并使用{{1}将它们传递给where }:

send

而不是所有这些,你应该只定义一个范围:

module ArtikelgroepsHelper
  def artikelgroeps_not_in_users_selection
    ['"id NOT IN (SELECT artikelgroep_id FROM user_artikelgroeps WHERE user_id = :uid)"', {uid: @user.id}]
  end
end

Artikelgroep.send(:where, *artikelgroeps_not_in_users_selection)

答案 1 :(得分:1)

将查询放入模型中:

模型

model Artikelgroep
  scope :without_user, (user) -> {
    joins(:user_artikelgroeps).where("user_artikelgroeps.user_id != ?", user.id)
  }
end

视图

<%= f.collection_select(:artikelgroep_id, Artikelgroep.without_user(@user), :id, :omschrijving) %>