如何在Rails中正确编写我的关系/关联?

时间:2015-06-30 22:04:06

标签: ruby-on-rails ruby-on-rails-4

我有4个模型,我不确定写关系/关联的正确方法是什么。

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

1 个答案:

答案 0 :(得分:0)

如果您想更明确地了解您的人际关系,请随意执行以下操作(在大多数情况下都是首选):

set @chksum = @chksum + (@chksum1 % 10)
-- Here -----------------^

最后,请确保您的任何依赖于其他模型的模型(例如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 belongs_to Board)在其表中具有相应的外键。因此,例如,User将需要一个Board外键来正确创建关联。

如果您还不喜欢,可以为任何这些实体创建迁移:

user_id