how to model a many to many relationship

Posted by Maulin on Stack Overflow See other posts from Stack Overflow or by Maulin
Published on 2010-01-28T01:37:56Z Indexed on 2010/06/03 7:04 UTC
Read the original article Hit count: 241

Filed under:

Here is the scenario, Articles have many Comments Users can write many Comments for many Articles

The comments table contains both

user_id
article_id

as foreign keys

My models are set up like so

class User < ActiveRecord::Base
  has_many :comments
  has_many :articles, :through => :comments

class Article < ActiveRecord::Base
  has_many :comments
  has_many :users, :through => :comments

class Comment < ActiveRecord::Base
  belongs_to :users
  belongs_to :articles

My routes.rb has the following code

  map.resources :articles, :has_many => :comments  
  map.resources :users, :has_many => :comments

which produces the following routes

new_article_comment
edit_article_comment
new_user_comment
edit_user_comment
etc...

This is not what I want (atleast not what I think I want), since comments must always be related to users and article, how can I get a route like so

new_user_article_comment
edit_user_article_comment

Then I could just do

new_user_article_comment_path([@user, @article])

to create a new comment

© Stack Overflow or respective owner

Related posts about ruby-on-rails