Tuesday 15 March 2011

postgresql - Rails Active Record multiple associations -



postgresql - Rails Active Record multiple associations -

i have rails app using postgres , active record, , can't fathom efficient associations between models.

i have model called article. article needs have format , 2/3 genres.

i need articles able listed format i.e. http://myapp.com/format/format-id/article-id

i need articles listed genre, so: myapp.com/genre/genre-name/article-id

i thinking genres , formats models has_many_and_belongs_to associations articles. each article has multiple genres, , 1 format, each genre has multiple articles.

i know should simple, can't find efficient route of making happen.

there's old railscasts episode goes through 2 ways many-to-many associations rails - should watch it: http://railscasts.com/episodes/47-two-many-to-many. it's old still relevant.

so, you've got articles, formats, , genres. since each article have 1 format, don't need has_and_belongs_to_many relationship there. article belongs_to format, , format has_many articles.

each row in articles table have format_id field indicate format belongs to.

the relationship between genres , articles many-to-many, bit trickier. @ database level, requires 'join table'. bring together table called articles_genres, , each row represents 1 genre 1 particular article has. so, it'd have genre_id column, , article_id column.

in terms of rails, there 2 ways this:

give articles_genres table it's own model. in case might want give table different name, indicate it's model in it's own right, not bring together table. phone call genreizations or don't give articles_genres table it's own model, , allow rails handle all.

i prefer first way - sense more in control, , leaves things more flexible future. but, either work. railscasts episode linked describes both ways.

if go first way, models you'll have:

class article < activerecord::base has_many :genreizations has_many :genres, through: :genreizations belongs_to :format end class format < activerecord::base has_many :articles end class genreization < activerecord::base belongs_to :article belongs_to :genre end class genre < activerecord::base has_many :genreizations has_many :articles, through: :genreizations end

and in sec way, models you'll have:

class article < activerecord::base has_and_belongs_to_many :genres belongs_to :format end class format < activerecord::base has_many :articles end class genre < activerecord::base has_and_belongs_to_many :articles end

ruby-on-rails postgresql activerecord associations

No comments:

Post a Comment