Optimus Pette
Optimus Pette

Reputation: 3400

How can i handle this Active Record validation?

I have three models, user, message and message_reply:

#user.rb

class User < ActiveRecord::Base
  has_many :message_replies
  has_many :sent_messages, class_name: "Message", foreign_key: :sendor_id
  has_many :received_messages, class_name: "Message", foreign_key: :receiver_id
end


#message.rb

class Message < ActiveRecord::Base
  belongs_to :Sendor, class_name: "user", foreign_key: :sendor_id
  belongs_to :Receiver, class_name: "user", foreign_key: :receiver_id
  has_many :message_replies
end

#message_reply.rb

class MessageReply < ActiveRecord::Base
  belongs_to :user
  belongs_to :message
end

I want to validate that the :user_id in MessageReply is either the sendor_id or receiver_id of the Message instance that this MessageReply instance belongs to.

Upvotes: 1

Views: 46

Answers (1)

phoet
phoet

Reputation: 18845

you use a custom validation method and implement the logic in your MessageReply class or wherever you see fit.

validates :check_user

def check_user
  [custom logic]
end

Upvotes: 1

Related Questions