【问题标题】:Rails find method :select alias as id?Rails 查找方法:选择别名作为 id?
【发布时间】:2011-07-01 11:09:39
【问题描述】:

我目前在我的 Rails 控制器操作之一中有一个 .find 方法 - 相关部分是:

.find(:all, :select => 'last_name as id, last_name as name')

我在尝试将 last_name 列别名为 id 时遇到一些奇怪的行为 - 如果我将其别名为其他任何东西,它工作正常(我可以做 last_name as xyz 并且它在名为 xyz 的列中输出姓氏,但作为我正在使用它来填充一个下拉列表,我需要在 id 列中有名称,我需要将其称为“id”)。

我应该指出它确实输出了一个 id 列,但它始终是"id":0

谁能阐明我需要做什么才能将此列别名为“id”?

谢谢!

【问题讨论】:

  • 如果有帮助,正在创建的 SQL(不会产生任何错误)是:SELECT last_name as id, last_name as name FROM "customers" INNER JOIN "dealerships" ON "dealerships"."id" = "customers"."dealership_id" WHERE ('t'='t')

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


【解决方案1】:

我不确定如何在 Rails 查询语句中执行此操作。 Rails 将尝试接管id 列,将数据库返回的值转换为idid 的列类型(可能是整数)。这就是为什么您的 id 列一直设置为 0,因为 "string".to_i #=> 0

但是,一旦您得到结果,就有办法做到这一点。

由于您将问题标记为 Rails 3,因此最好使用新的 ActiveRelation 语法。您可以执行以下操作:

# First, get the results from the query, then loop through all of them.
Customer.select("last_name as 'ln', last_name as 'name'").all.collect do |c|
  # The first step of the loop is to get the attributes into a hash form
  h = c.attributes
  # The next step is to create an "id" key in the hash.
  # The Hash#delete method deletes the key/value pair at the key specified and returns the value.
  # We'll take that returned value and assign it to the just created "id" key.
  h["id"] = h.delete("ln")
  # And we have to call out the hash to ensure that it's the returned value from the collect.
  h
end

这将为您提供一个哈希值,其中 id 值作为文本字符串值 last_namename 值相同。

希望有帮助!

【讨论】:

    【解决方案2】:

    您不需要在查找器 SQL 中设置别名来填充下拉列表。相反,只需将 last_name 值用于 value 属性(以及显示文本)。

    例如,如果您正在使用 collection_select 帮助器:

    <%= f.collection_select :attribute_id, @collection, :last_name, :last_name %>
    

    【讨论】:

    • 抱歉,我应该更具体一些 - 上面提到的代码在我的控制器中,它正在填充一个 jQuery 下拉列表(链接到其他下拉列表)。下拉列表由 JSON 对象填充,它使用 JSON 中的 id 列填充隐藏字段 - 在这种情况下,我需要隐藏字段中的值为 last_name,以便它可以将其传递给下一个字段。
    猜你喜欢
    • 2018-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-30
    • 1970-01-01
    • 1970-01-01
    • 2017-10-02
    相关资源
    最近更新 更多