开发者

HABTM relationship with an array

开发者 https://www.devze.com 2023-02-02 08:01 出处:网络
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

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开发者_C百科 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


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


Following egze's suggestion, I found a way to solve my problem (without using arrays!). So, I create a has_many-through relationship, but as I want to save the order for the articles how they are mentioned in the bibliography, the table articles_bibliographies has also a order_nr field, where I store which is the first, second, etc. article mentioned in the bibliography:

create_table :articles_bibliographies do |t|
   t.references  :article
   t.references  :bibliography
   t.integer     :order_nr

This way I can retrieve and show an ordered list of elements with:

@bibliography.articles.order("order_nr ASC")
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号