用户和文件的多对多关系以及它在rails中的所有权

时间:2013-12-21 03:37:13

标签: ruby-on-rails many-to-many

如何在多对多关系中添加所有权?

例如像这个型号。

class User < ActiveRecord::Base
  has_many :editabilities, dependent: :destroy
  has_many :files, through: :editabilities
end

class File < ActiveRecord::Base
  has_many :editabilities, dependent: :destroy
  has_many :users, through: :editabilities
end

class Editabilities < ActiveRecord::Base
  belongs_to :user
  belongs_to :file
end

我想为User-and-Files添加一对多的关系。

起初我认为最好将owner布尔列添加到Editabilities,但我不知道如何处理它。

其次我想如果我创建一个新的联结模型Ownerships,那么我可以像Editabilities一样处理它。但是当我用这样的代码尝试它时,我得到了uninitialized constant User::Ownership

class User < ActiveRecord::Base
  has_many :editabilities, dependent: :destroy
  has_many :ownerships, dependent: :destroy
  has_many :files, through: :editabilities
  has_many :owned_files, through: :ownerships, source: :file
end

class File < ActiveRecord::Base
  has_many :editabilities, dependent: :destroy
  has_many :ownerships, dependent: :destroy
  has_many :users, through: :editabilities
  has_one :owner, through: :ownerships, source: :user
end

class Editabilities < ActiveRecord::Base
  belongs_to :user
  belongs_to :file
end

class Ownerships < ActiveReord::Base
  belongs_to :user
  belongs_to :file
end

如何实现这样的功能?

2 个答案:

答案 0 :(得分:0)

您的课程应该被命名为Ownership,而不是Ownerships。 ActiveRecord类名通常是单数,表名是复数。

更简单的解决方案似乎将belongs_to关联添加到文件模型。因为1个文件只能拥有1个所有者。

class File < ActiveRecord::Base
  ...
  belongs_to :owner, class_name: 'User'
end

您需要将owner_id列添加到文件表。

答案 1 :(得分:0)

我在这里看到的唯一问题是课程EditabilitiesOwnerships。通过Rails约定模型类名应该是单数,而不是复数。

class Editability < ActiveRecord::Base
  belongs_to :user
  belongs_to :file
end

class Ownership < ActiveReord::Base
  belongs_to :user
  belongs_to :file
end

快速检查班级名称的一种方法是检查classify函数的结果:

> "editibilities".classify 
=> "Editibility" 

> "ownerships".classify
=> "Ownership"

其余的协会看起来都是正确的。