Ian Bernatcki
Ian Bernatcki

Reputation: 108

How to use :inverse_to in ActiveRecord

:inverse_to doesn't work with my complex case

class Communication::Message < ActiveRecord::Base
  belongs_to :conversation_for_proposal, {
    :class_name  => 'Communication::Conversation::ForProposal',
    :foreign_key => :conversation_id,
    :inverse_of  => :messages_for_proposal
  }
end

class Communication::Conversation::ForProposal < ActiveRecord::Base
  has_many :messages_for_proposal, {
    :class_name  => 'Communication::Message',
    :foreign_key => :conversation_id,
    :inverse_of  => :conversation_for_proposal
  }
end

Problem: Communication::Conversation::ForProposal doesn't know about messages

Communication::Conversation::ForProposal.new.messages_for_proposal.build.conversation_for_proposal # => ok

Communication::Message.new.build_conversation_for_proposal.messages_for_proposal # => []

Reflections:

Communication::Message.reflect_on_association(:conversation_for_proposal).active_record
# => Communication::Message

Communication::Message.reflect_on_association(:conversation_for_proposal).inverse_of.active_record
# => Communication::Conversation::ForProposal

What I miss?

Upvotes: 1

Views: 246

Answers (1)

makaroni4
makaroni4

Reputation: 2281

You need to specify the :inverse_of option.

class Post < AR::Base
  has_many :comments, :inverse_of => :post
end

class Comment < AR::Base
  belongs_to :post, :inverse_of => :comments
end

Upvotes: 1

Related Questions