2

I have some question about RoR and MongoDB(use gem mongoid). For example I have two collection- users(fields: id, username, age) and messages(fields: id, message, user_to, user_from). I need to relate this collections. The model user-

....
has_many :messages

The model message-

....
belongs_to :to_user, :class_name => 'User', :foreign_key => 'user_to'
belongs_to :from_user, :class_name => 'User', :foreign_key => 'user_from'

Call in my view-

- @messages.each do |message|
  %tr
    %td    
      = message.message
    %td
      = message.to_user.username
    %td
      = message.from_user.username

But it not working. Please tell me how to relate it. B.R.

1 Answer 1

3

You have to provide inverse relation

belongs_to :to_user, :class_name => 'User', :inverse_of => :recieved_messages
belongs_to :from_user, :class_name => 'User', :inverse_of => :sent_messages

user.rb

has_many :recieved_messages, :class_name => 'Message', :inverse_of => :to_user
has_many :sent_messages, :class_name => 'Message', :inverse_of => :from_user

And you don't need the foreign_key, Mongoid will take care of it

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. But sorry, Mongoid not take care of it without foreign_key. I pointed foreign_key and this working well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.