【问题标题】:rails how to add in :include for a multiple index key associationrails 如何在 :include 中添加多索引键关联
【发布时间】:2011-08-01 14:01:16
【问题描述】:

我已经开始按照这里的指南Rails - Multiple Index Key Association

我试图添加 :include 以加快关联,但我得到了这个错误:

ActiveRecord::StatementInvalid in ItemsController#show

SQLite3::SQLException: no such column: links.item_id: SELECT "links".* FROM "links" WHERE ("links".item_id = 19)

这是我所拥有的:

item.rb

 class Item < ActiveRecord::Base
    has_many :links, :dependent => :destroy, :uniq => true
    belongs_to :category
    belongs_to :user

    is_sluggable :name

     def links
      Link.by_item(self)
     end

链接.rb

class Link < ActiveRecord::Base
  belongs_to :item1, :class_name => 'Item', :foreign_key => :item1_id
  belongs_to :item2, :class_name => 'Item', :foreign_key => :item2_id
  belongs_to :user
  validates_presence_of :item1_id
  validates_presence_of :item2_id
  validates_uniqueness_of :item1_id, :scope => :item2_id, :message => "This combination already exists!"

  def self.by_item(item)
    where("item1_id = :item_id OR item2_id = :item_id", :item_id => item.id)
  end
end

items_controller.rb

  def show
    @item = Item.find_using_slug(params[:id], :include => [:category, :user, :links])

在 :include 中没有 :links 也能正常工作。但否则我会得到错误。

据我了解,item_id 作为 item1_id 或 item2_id 存储在链接表中,这就是找不到它的原因。是否有解决方法,因为我将大量引用链接记录。我不太擅长 SQL 的东西。

也不确定设置索引的最佳方法是什么

愿意尝试任何建议。谢谢

【问题讨论】:

    标签: ruby-on-rails include indexing


    【解决方案1】:

    问题在于Item 中的has_many :links 关联设置。默认情况下,这会转换为 SQL 查询,该查询会查找所有具有当前Itemitem_id 的链接。要覆盖此默认行为,请自行指定 find SQL,如下所示:

    has_many :links, :dependent => :destroy, :uniq => true, :finder_sql => 'SELECT DISTINCT(*) FROM links WHERE item1_id = #{id} OR item2_id = #{id}'
    

    【讨论】:

    • links 表有一个 item1_id 和 item2_id,因为它用于 item 表中两个项目之间的链接
    • 啊,现在我明白了。您正在尝试将两个项目配对(链接)在一起,并且每对只执行一次。我不确定您是否可以建立这样的关联。 has_many :links 关联会查找所有具有当前项目主键 (id) 的 item_id 值的链接。你至少可以做 has_one :link_1 和 has_one :link_2。
    • 哦,我想您可以使用 has_many 定义如何获取关联。您可以在其中定义自定义 SQL 查询。让我检查一下文档。
    • 嗯,很明显,Rails 默认情况下并不急切地获取关联。在您的控制台中尝试此操作以了解:item = Item.first 然后 item.links。第一个语句应该起作用,第二个语句会中断。添加上面的自定义查找 SQL,它应该可以工作。
    • 实际上这两种说法都有效。我尝试添加修改后的 SQL 语句,它在 ItemsController#show undefined local variable or method `id' for #<0x007ff504a587b8>
    猜你喜欢
    • 2011-03-26
    • 1970-01-01
    • 2013-09-26
    • 1970-01-01
    • 2015-02-13
    • 2010-09-23
    • 2015-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多