【发布时间】: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