1

I am bit confused with these issue

Here is the Item model

class Item < ActiveRecord::Base
  has_many :true_items, :foreign_key => "parent_id", dependent: :destroy
end

Here is the TrueItem model

class TrueItem < ActiveRecord::Base
  attr_accessible :item_id, :parent_id

  belongs_to :parent, :class_name => "Item"
  belongs_to :item
end

Here am taking all the items includes true_items

items = Item.includes(:true_items)
items.each do |item|
   item.true_items.each do | true_item |
      true_items = "#{true_item.item.name}"
   end
end

Here the problem is, when i am taking the item.name like "#{true_item.item.name}" in the loop, duplicate query happening, that means again calling that item get the name. is there any issue with that association?

Developer
  • 561
  • 7
  • 29

2 Answers2

3

This is happening because you have two associations, to parent and to item.

You could just call the right association in your loop:

Item.includes(:true_items).each do |item|
   item.true_items.each do |true_item|
      true_items = "#{true_item.parent.name}"
   end
end

Or you could actually just add an alias to your association (since item and parent is actually the same association):

class TrueItem < ActiveRecord::Base
  attr_accessible :item_id, :parent_id

  belongs_to :parent, :class_name => "Item"
  alias_attribute :item, :parent
end
Yury Lebedev
  • 3,985
  • 19
  • 26
  • Thanks, but is not avoiding the duplication – Developer Oct 01 '15 at 11:55
  • Also i cannot use parent.item, because the item and parent is different, here i am taking TrueItem name, but when we use the parent, its giving from the table (Item).name – Developer Oct 01 '15 at 12:42
0
#app/models/item.rb
class Item < ActiveRecord::Base
   has_and_belongs_to_many :true_items,
        class_name: "Item", 
        join_table: :true_items, 
        foreign_key: :item_id, 
        association_foreign_key: :true_item_id
end

Reference

This will allow you to call the following:

<% @items = Item.all %>
<% @items.each do |item| %> 
   <% item.true_items.each do |true_item| %>
      <%= true_item.name %>
   <% end %>
<% end %>

You'll even be able to keep your true_items table (you may have to remove the id, created_at & updated_at fields.

Community
  • 1
  • 1
Richard Peck
  • 76,116
  • 9
  • 93
  • 147