2015-06-30 44 views
0

我有4个模型,我不知道什么是写我的关系/协会的正确方法。如何在Rails中正确编写我的关系/关联?

class User < ActiveRecord::Base 
    has_many :boards 
    has_many :lists 
    has_many :cards 
end 

class Board < ActiveRecord::Base 
belongs_to :user 
has_many :lists 
end 


class List < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :board 
    has_many :cards 
end 

class Card < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :list 
end 
+0

这看起来好像没什么问题。你能详细了解你需要他们如何行事或目前没有工作吗? – PhilVarg

回答

0

如果你想更明确的了解你的人际关系,随时做(首选在大多数所有情况下)以下:

class User < ActiveRecord::Base 
    has_many :boards, inverse_of: :user, dependent: :destroy 
    has_many :lists, inverse_of: :user, dependent: :destroy 
    has_many :cards, inverse_of: user, dependent: :destroy 
end 

class Board < ActiveRecord::Base 
belongs_to :user, inverse_of: :boards 
has_many :lists, inverse_of: :board 
end 


class List < ActiveRecord::Base 
    belongs_to :user, inverse_of: :lists 
    belongs_to :board, inverse_of :lists 
    has_many :cards, inverse_of :list 
end 

class Card < ActiveRecord::Base 
    belongs_to :user, inverse_of: :cards 
    belongs_to :list, inverse_of :cards 
end 

最后,确保你的任何模型依赖的(例如Boardbelongs_toUser)在其表中具有适当的外键。因此,例如,Board将需要有一个user_id外键才能正确创建关联。

,如果您还没有像这样您可以创建任何这些实体的迁移:

rails generate migration AddUserRefToBoards user:references

相关问题