Ruby on rails - Reference the same model twice?

Viewed 28484

Is it possible to set up a double relationship in activerecord models via the generate scaffold command?

For example, if I had a User model and a PrivateMessage model, the private_messages table would need to keep track of both the sender and recipient.

Obviously, for a single relationship I would just do this:

ruby script/generate scaffold pm title:string content:string user:references

Is there a similar way to set up two relations?

Also, is there anyway to set up aliases for the relations?

So rather than saying:

@message.user

You can use something like:

@message.sender or @message.recipient

Any advice would be greatly appreciated.

Thanks.

4 Answers

Add this to your Model

belongs_to :sender, :class_name => "User"
belongs_to :recipient, :class_name => "User"

And you are able to call @message.sender and @message.recipient and both reference to the User model.

Instead of user:references in your generate command, you'd need sender:references and recipient:references

Related