Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I associate one model twice to another

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.

Ill need functionality like

-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

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.

like image 266
robodisco Avatar asked Apr 09 '10 10:04

robodisco


1 Answers

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.

like image 183
Milan Novota Avatar answered Nov 01 '22 16:11

Milan Novota