简体   繁体   中英

Communication between two unrelated classes in rails?

I'm fairly new to rails and I've run into a scenario that I'm having trouble solving "the right way".

Let's say I have a few models:

  • Comment
  • Article
  • Photo
  • Video

Comments can be made on Articles, Photos, Videos and other Comments (as replies). More generally, comments can potentially be made on any object.

What I need is to be able to call methods on the object that the comment was made on (without knowing what that object is).

My current strategy is to rely on duck typing and simply define an informal "protocol" for accessing properties I need.

In my Comment class I have a method commentable_object which returns the thing that was commented on (either a Photo, Video, Article or Comment). Then on this commentable_object I call two methods: notification_user and notification_object . It's the responsibility of the commetable_object to implement notification_user and notification_object and return the appropriate thing.

在此输入图像描述

The details of these methods is not important, what's important is that my Comment class needs to request specific data from some class (which can be anything).

The problem is I don't want all these different classes to know about the Comment class. Right now I'm relying on duck typing and simply checking respond_to on these objects. It just feels weird for Article, Photo and Video to implement methods that are needed by the Comment class when really they shouldn't know anything about it. Is there perhaps a better place to implement these methods?

What's the most elegant way to implement this in rails?

UPDATE

Just to be a bit more clear, I'm not looking for ways to model the relationships between these objects. My question is really about how to cleanly define an "interface" used between two objects but without those two objects knowing about each other.

in rails it is called polymorphic associations see this, it may help:

http://railscasts.com/episodes/154-polymorphic-association

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM