HanXu
HanXu

Reputation: 5597

How can I define multiple has_and_belongs_to_many in Rails?

I have two model: User, Article

A user can like or dislike many articles, and an article can be liked or disliked by many users. So I need to build a many-to-many relation between them.

In rails, I think I need to use has_and_belongs_to_many..

I think the structure of the code is like below:

class User
    has_and_belongs_to_many :liked_articles
    has_and_belongs_to_many :disliked_articles
end

class Article
    has_and_belongs_to_many :liking_users
    has_and_belongs_to_many :disliking_users
end

Of course, the code above doesn't work.

But I don't know what the right code is. Who can help me?

Updated:

I came up with such code:

class User
    has_and_belongs_to_many :liked_articles, :class_name => 'Article', :join_table => 'articles_users_like', :uniq => true
    has_and_belongs_to_many :disliked_articles, :class_name => 'Article', :join_table => 'articles_users_dislike', :uniq => true
end

class Article
    has_and_belongs_to_many :liking_users, :class_name => 'User', :join_table => 'articles_users_like', :uniq => true
    has_and_belongs_to_many :disliking_users, :class_name => 'User', :join_table => 'articles_users_dislike', :uniq => true
end

I think it will work.

but as both Peter Sobot and Jon McIntosh said, nowadays has_many, :through is more preferred. Can you tell me why? The latter one is logically more clear than has_and_belongs_to?

Upvotes: 2

Views: 1730

Answers (2)

Jon McIntosh
Jon McIntosh

Reputation: 1263

These association methods are tied to Models. Unless you have a Liking_User and a Disliking_User model, this clearly won't work. Apart from that I believe that you're going at this the wrong way.

Let's break this problem down for a moment. You have a User and an Article. Your Article needs to have functionality to be disliked and liked by Users, correct? I'm going to visualize it sort-of like the SO/Reddit reputation system and assume that the User can like or dislike an Article once. For this I would create a separate model for voting, called Votes and tie it all together with a has_many, :through association.

User.rb

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

Article.rb

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

Vote.rb

  class Vote < ActiveRecord::Base
     belongs_to :user
     belongs_to :article
  end

Now that these associations are set up, the models are going to be looking for a few fields in the database. The structure should look something like this:

Users
+----+-----------+
| id | user_name | 
+----+-----------+    

Articles
+----+--------+
| id |  title |
+----+--------+

Votes
+----+----------+------------+-------+
| id |  user_id | article_id | value |
+----+----------+------------+-------+

This completes the association by giving the model an ID to reference. Now you can witness the rails magic when you create that vote entry...

class ArticlesController < ApplicationController
  def like
    @article = Article.find(params[:article_id])
    @article.votes.create(:user_id => current_user, :value => 1)

    respond_to do |format|
      if @article.save
        format.html { redirect_to @article, notice: 'Article was successfully liked.' }
        format.json { head :no_content }
      else
        format.html { redirect_to @article, notice: 'Article was unsuccessfully liked.' }
        format.json { render json: @article.errors, status: :unprocessable_entity }
      end
    end

  end
end

EDIT: Per your comment, the has_and_belongs_to_many and has_many :through relationships are very similar... You have two models and a join table to hold the ref data. The difference between the two is that has_many :through requires a third model which is interacted with between the relationship (like say, users/articles/votes).

The reason why has_many :through is more widely recommended is that it's more flexible and you're given more to work with as opposed to the latter. In your case you must create this relationship because you need the third model to tally your votes.

The logic that you're following right now institutes a principal to create four Models, and would require updating specific ones based upon the action that the user wants to take. This is absolutely not the rails (or any logical) way of doing things. Keep it simple.

Ruby on Rails Guides: A Guide to Active Record Associations

Upvotes: 4

Peter Sobot
Peter Sobot

Reputation: 2557

has_and_belongs_to_many is considered somewhat outdated nowadays - you probably want to use has_many :through in this case. Consider using one table for "votes" and doing something like this:

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

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

class Vote < ActiveRecord:Base
    belongs_to :article
    belongs_to :user
end

You could then add a "sign" field to vote to show if it's an upvote or downvote, and then filter on that.

Upvotes: 3

Related Questions