所以我试图在3个模型之间建立关系。项目,类别&交易。
每个项目属于一个类别,类别可以有多个项目。
Class User
end
Class Item
belongs_to :category
has_many :transactions
end
Class Category
has_many :items
end
Class Categorization
belongs_to :item
belongs_to :category
end
Class Transactions
belongs_to :user
has_many :items
end
我遇到的问题是,我希望用户能够创建项目,而不必将它们绑定到事务。目前,当我运行Rspec时,我收到错误“Expected Transaction有一个名为items的has_many关联(Item没有transaction_id外键)。有关我可能做错的任何想法?
答案 0 :(得分:1)
当你说,在交易类中(这应该是交易(单数),那只是一个错字吗?)
has_many :items
rails期望items表具有事务ID,并且对belongs_to:items
你有
has_many :transactions
在项目中,这表明他们有“拥有并且属于许多”的关系。如果是这种情况,那么您应该创建一个将项目和事务链接在一起的连接表/模型。同样,您的项目和类别之间的关系看起来同样困惑。它们是否意味着“拥有并属于许多”关系?我认为您可能希望它设置如下:
Class Item
has_many :item_transactions, :dependent => :destroy
has_many :transactions, :through => :item_transactions
has_many :categorizations, :dependent => :destroy
has_many :categories, :through => :categorizations
end
class ItemTransaction
#has fields item_id, transaction_id
belongs_to :item
belongs_to :transaction
end
Class Category
has_many :categorizations, :dependent => :destroy
has_many :items, :through => :categorizations
end
Class Categorization
#has fields item_id, category_id
belongs_to :item
belongs_to :category
end
Class Transaction
#has field user_id
belongs_to :user
has_many :item_transactions, :dependent => :destroy
has_many :items, :through => :item_transactions
end