我怎么一个模型两次,彼此相关联 [英] how do I associate one model twice to another

查看:115
本文介绍了我怎么一个模型两次,彼此相关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

喜IM做一个小网站,以帮助我和朋友们学习语言。
典型用途:

Hi im making a small site to help me and friends learn languages. Typical use:

亚当是英语,但学习日语。
亚当可以通过编写和提交书面日语文章练习他的日本。
亚当斜面(不准)提交书面在他的母语的任何物品。
亚当可以阅读的文章(用英文写的),其他用户谁是学习英语

Adam is english but is learning japanese. Adam can practice his japanese by writing and submitting articles written in japanese. Adam cant (not allowed to) submit any articles written in his native language. Adam can read articles (written in English) by other users who are learning English

我试着去思考如何建模这个和它的证明是更困难比标准轨有很多属于这个我真的习惯协会。

Im trying to think how to model this and its proving to be more difficult than the standard rails has many belongs to associations that I`m accustomed to.

生病需要像

-show all articles written in adams native language
@adam.native_language.articles

-show all posts written by users just like adam (i.e. learning the same language)
@adam.foreign_language.articles

-perhaps showing all posts written by language learners in one particular language
@language => Japanese
@langauge.posts

我需要一个用户,文章和语言模型。但我怎么了语言和用户模型相关联?这感觉就像语言应与之关联两次以用户模型,一次native_language和一次FOREIGN_LANGUAGE。

I need a user, article and language model. But how do i associate the language and user models? It feels like language should be associated twice to the user model, once for native_language and once for foreign_language.

推荐答案

是啊,你说得对。用户和语言之间的关联是双重的。这是很容易使用Rails这种情况型号:

Yeah, you're right. The association between User and Language is twofold. It's quite easy to model this situation using Rails:

class Language < AR::Base
  has_many :native_speakers, :class_name => "User", :foreign_key => "native_language_id"
  has_many :second_language_speakers, :class_name => "User", :foreign_key => "second_language_id"
  has_many :articles
end

class User < AR::Base
  # we expect the users table to have native_language_id and second_language_id columns
  belongs_to :native_language, :class_name => "Language"
  belongs_to :second_language, :class_name => "Language"
  has_many :second_language_articles, :through => :second_language, :source => :articles
  has_many :native_language_articles, :through => :native_language, :source => :articles
end

class Article < AR::Base
  belongs_to :language
end

这样的东西应该工作。

Something like that should work.

这篇关于我怎么一个模型两次,彼此相关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆