Search code examples
ruby-on-railsarraysrelationships

HABTM relationship with an array


I am a beginner with Rails 3 programming and I have one problem with creating the right model.

Let's say there is an application to manage the bibliography of a book, that is manage the mapping for each chapter of the list of referenced articles. So for the article part I could have something like:

create_table :articles do |t|
  t.string :title
  t.text   :content
  ...

On the bibliography side I would like to have a model like

create_table :bibliographies do |t|
  t.string :chapter
  t.text   :ref
  ...

where ref is actually an array of references to articles, so it would be managed via serialize ActiveRecord method.

Ok, so now the issue is about how to make so that the elements of the array @bibliography.ref are references (in Ruby sense) to several article_id.

How do I model such a relationship, and what Rails 3 code should I write to express that? The thing that confuses me is that a single field of a single instance of @bibliography would reference to many @article.id .

Thanks in advance


Solution

  • If you really want to store relationships like that, then I would define a method in Bibliography model, something like this

    (Assuming that ref is an array of ids)

    def articles
      Article.where(:id => self.ref)
    end
    

    I would store the relationship differently though. Add a third table/model articles_bibliographies with article_id and bibliography_id fields. Then you can use the has_many :through association which is built into ActiveRecord.

    in your Bibliography class you would then have something like:

    has_many :articles_bibliographies
    has_many :articles, :through => :articles_bibliographies
    

    then you can just do @bibliography.articles

    Read more here http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association