ClassyPimp
ClassyPimp

Reputation: 725

rails 4 HABTM relation and extra fields on join table

What I have (pseudo code):

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

Document has users (being approvers for document, either approve or not), and in this context join table should have extra column approved for each user.

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

What I want is basically:

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

Answer right for this situation is optional, will appreciate advises on schema too (or maybe i should use other type of relation?).

Upvotes: 0

Views: 885

Answers (1)

Austio
Austio

Reputation: 6085

HABTM has been deprecated a while ago, I think it is just a reference to has many through now.

Either way

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

I don't understand how contract fits into this, i think you are saying that a document is a contract?

I would put the approve method in a separate class

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

end

Upvotes: 1

Related Questions