多对多关联的模糊列名称

时间:2014-01-30 18:48:13

标签: ruby-on-rails ruby-on-rails-4 associations rails-activerecord

我正在尝试为多对多关系创建复选框。

project可以有多个graphsgraph可以属于许多projects

我正在关注this question的答案,并使用collection_check_boxes()。

<%= collection_check_boxes(:project, :user_graph_ids, UserGraph.all, :id, :title) %>

结果是关于模糊列的SQL错误。为什么会这样?

SQLite3::SQLException: ambiguous column name: created_at: 
  SELECT "user_graphs".id 
  FROM "user_graphs" 
  INNER JOIN "project_user_graphs" 
  ON "user_graphs"."id" = "project_user_graphs"."user_graph_id" 
  WHERE "project_user_graphs"."project_id" = ?  
  ORDER BY created_at DESC

1 个答案:

答案 0 :(得分:1)

强制UserGraph.all的排序使用created_at表中的user_graphs

<%= collection_check_boxes(:project, :user_graph_ids, UserGraph.all.order("user_graphs.created_at ASC"), :id, :title) %>

注意:我最终会将其作为范围推送到UserGraph模型中:

class UserGraph < ActiveRecord::Base
  def self.ordered(direction="asc")
    order("user_graphs.created_at #{direction}")
  end
end

<%= collection_check_boxes(:project, :user_graph_ids, UserGraph.all.ordered, :id, :title) %>