Matrix
Matrix

Reputation: 3369

relation has_many rails with inheritance

i have :

class Character < ActiveRecord::Base
  has_many :items, through: :character_items
  has_many :character_item
end

class Item < ActiveRecord::Base
class Weapon < Item
class Armor < Item

i want to be abble :

myCharacter.weapons

has_many :weapons, through: :character_items dont work, i just want the same as items but filter with "type" column to get only weapon objects.

thx for help

PS: i'm on Rails 4

Upvotes: 0

Views: 86

Answers (1)

Tala
Tala

Reputation: 8928

has_many :weapons, through: :character_items, conditions: {character_items: {type: "weapon"}}, class_name: "Item", source: :item

hope that helps

edit answer from Matrix:

 has_many :weapons, { through: :character_items, source: :item }, -> { where(type: 'Weapon') } 

Upvotes: 1

Related Questions