Developer
Developer

Reputation: 661

Rails association with foreign key

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?

Upvotes: 1

Views: 470

Answers (2)

Richard Peck
Richard Peck

Reputation: 76774

#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.

Upvotes: 0

Yury Lebedev
Yury Lebedev

Reputation: 4005

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

Upvotes: 3

Related Questions