0

I'm trying to join the results of 'SupplierShippingItem' and 'MtlSystemItem' but I keep getting an error:

Association named 'mtl_system_items' was not found; perhaps you misspelled it?

My association is done like this:

SupplierShippingItem.joins(:mtl_system_items).where('supplier_shipping_items.inventory_item_id = mtl_system_items.inventory_item_id SEGMENT1 ILIKE ? OR DESCRIPTION ILIKE ? ', "%#{params[:term]}%", "%#{params[:term]}%")

SupplierShippingItem

class SupplierShippingItem < ActiveRecord::Base

  attr_accessible :inventory_item_id, :received_qty, :shipped_qty, :supplier_shipping_list_id, :supplier_planning_schedule_id, :po_number

  belongs_to :mtl_system_item, :foreign_key => :inventory_item_id


end

*MtlSystemItem *

class MtlSystemItem < ActiveRecord::Base

  attr_accessible :inventory_item_id, :segment1, :description, :primary_uom_code, :inventory_item_status_code, :item_type

  has_many :supplier_shipping_items, :foreign_key => :inventory_item_id
end

What I'm trying to achieve is to fetch the items in MtlSystemItem but only if they are found in SupplierShippingItem. I have thousands of items in MtlSystemItem so I want to filter them out a bit. I'll also include a date restriction later on, but I'm blocked by the error.

4

2 回答 2

2

正如错误所说,没有找到关联。您使用mtl_system_items而不是mtl_system_item(singular) 这是您声明的关联。

请记住,对于joinsand includes,您需要使用关联名称。对于where,使用表名

SupplierShippingItem.joins(:mtl_system_item)
  .where('supplier_shipping_items.inventory_item_id = mtl_system_items.inventory_item_id SEGMENT1 ILIKE ? OR DESCRIPTION ILIKE ? ', "%#{params[:term]}%", "%#{params[:term]}%")
于 2013-05-03T02:22:23.020 回答
1
SupplierShippingItem.joins(:mtl_system_items)


 should be


SupplierShippingItem.joins(:mtl_system_item)

在你上面的例子中:

class SupplierShippingItem < ActiveRecord::Base
  belongs_to :mtl_system_item
end

class MtlSystemItem < ActiveRecord::Base
   has_many :supplier_shipping_items
end

你可以试试这个 ActiveRecord 连接:

SupplierShippingItem.find(:all, :joins => :mtl_system_item])

您可以像这样为此查询添加条件:

 SupplierShippingItem.find(:all, :joins => :mtl_system_item, :conditions => ["supplier_shipping_items.id = ?", 1]])
于 2013-05-03T04:13:14.187 回答