【问题标题】:ActiveRecord::StatementInvalid when trying to sort on an associated field.尝试对关联字段进行排序时,ActiveRecord::StatementInvalid。
【发布时间】:2016-06-06 14:30:10
【问题描述】:

我正在尝试根据关联字段对结果进行排序。我发现帖子表明这可以通过包含来完成。

我有一个观察模型

  before_validation   :parse_supervisor, :parse_employee

  has_many :attachments, :dependent => :destroy
  accepts_nested_attributes_for :attachments

  belongs_to :user, foreign_key: "employee_id", class_name: "User"
  belongs_to :user, foreign_key: "supervisor_id", class_name: "User"
  belongs_to :department

我有一个包含以下内容的 user.rb。 User.rb 也与 adauth 一起用于活动目录集成,但我认为这不会导致问题。

class User < ActiveRecord::Base


  has_many :subordinates, class_name: "User", foreign_key: "supervisor_id"

  belongs_to :supervisor, class_name: "User"
   has_many :observations

我的部分观察\index.rb 如下。用户。

 <% @observations.each do |observation| %>
      <tr>
        <td><%= observation.employee_id %></td>
        <td><%= observation.user.first_name %></td>
        <td><%= observation.user.last_name %></td>
        <td><%= observation.user.id %></td>
        <% d = observation.date %>
        <td style="text-align: center;"><%= d.strftime("%m/%d/%y") %></td>
        <td><%= observation.status %></td>

observation.user.first_name 和 last_name 用于显示。

我的观察控制器有

 def index
    @observations = Observation.all
    @users = User.all
    get_ldap('*', '*')
    @observations = Observation.includes([:users]).order('[user].last_name ASC')

我将 user 放在括号 [] 中,因为 user 似乎是 sql 中的保留字。

我得到的错误是

ActiveRecord::StatementInvalid in Observations#index
Showing C:/Users/cmendla/RubymineProjects/employee_observations/app/views/observations/index.html.erb where line #23 raised:

TinyTds::Error: The multi-part identifier "user.last_name" could not be bound.: EXEC sp_executesql N'SELECT [eo].[observations].* FROM [eo].[observations]  ORDER BY [user].last_name ASC'
Rails.root: C:/Users/cmendla/RubymineProjects/employee_observations

Application Trace | Framework Trace | Full Trace
app/views/observations/index.html.erb:23:in `_app_views_observations_index_html_erb__594730326_70277244'
Request

Parameters:

None

我的总体目标是能够根据用户模型的姓氏(和名字)对观察表中的记录进行排序。注意 - 我正在为数据库使用 MS Sql Server。

【问题讨论】:

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


    【解决方案1】:

    我认为错误在这里改变它:

    @observations = Observation.includes(:user).order('users.last_name ASC')
    

    【讨论】:

    • 另外,我的模型/表中没有 user_id 列。 (我最初是链接到一个员工模型)一旦我添加了它并将您的线路更改为@observations = Observation.includes(:user).order('users.last_name ASC') 它就起作用了。
    猜你喜欢
    • 2011-12-15
    • 2019-04-01
    • 1970-01-01
    • 2021-07-06
    • 1970-01-01
    • 1970-01-01
    • 2023-01-20
    • 1970-01-01
    • 2021-03-28
    相关资源
    最近更新 更多