【问题标题】:rails 4 HABTM relation and extra fields on join tablerails 4 HABTM 关系和连接表上的额外字段
【发布时间】:2015-04-10 00:29:33
【问题描述】:

我有什么(伪代码):

model Document
    column :title
    HABTM  :users
model User 
    column :name
    HABTM  :documents

文档有用户(作为文档的批准者,无论是否批准),在这种情况下,连接表应该为每个用户批准额外的列。

jointable
    user_id, document_id, approved
    1      , 1          ,    true
    2      , 1          ,    false

我想要的基本上是:

contract.approvers => returns users but with possibility to =>
contract.approvers.first.approve(:true) => and it updates JOINtable approve column to TRUE.

这种情况的正确答案是可选的,也会感谢有关架构的建议(或者我应该使用其他类型的关系?)。

【问题讨论】:

  • 连接表仅此而已。如果您想要连接对象上的列,您需要查看has_many through 关系。我的直觉告诉我,HABTM 和 has_many through 都不是这种情况下的正确关系。我不知道我是否理解得足以提出更好的建议。

标签: ruby-on-rails join entity-relationship has-and-belongs-to-many


【解决方案1】:

HABTM 已经被弃用了一段时间,我认为它只是一个参考,现在有很多。

不管怎样

join table name = DocumentReview

Document 
  has_many :document_reviews
  has_many :users, through: :document_reviews

User
  has_many :document_reviews
  has_many :documents, through: :document_reviews

我不明白合同如何适用于此,我认为您是说文件就是合同?

我会将approve方法放在一个单独的类中

class DocumentSignOff

  def initialize(user, document)
    @document_review = DocumentReview.find_by(user: user,document: document)
  end 

  def approve!
    #maybe more logic and such
    @document_review.udpate(approved: true)
  end
end

结束

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-21
    • 1970-01-01
    • 2015-12-02
    相关资源
    最近更新 更多