PonderingDonkey
PonderingDonkey

Reputation: 11

Add/Update users to Articles Rails

I have an article with a many relationship to users and vice versa. When I create an article signed in as a user, the article is created with the relationship to user. So the relationship is working. I want other users to be able to join this article, so essentially, I would like a button to push the current_user to the array/list of many users.

I am at a complete loss at how to go about this process... Any help is appreciated

Upvotes: 1

Views: 53

Answers (2)

Richard Peck
Richard Peck

Reputation: 76774

#app/models/user.rb
class User < ActiveRecord::Base
   has_many :written_articles, class_name: "Article", foreign_key: :user_id
   has_and_belongs_to_many :articles
end

#app/models/article.rb
class Article < ActiveRecord::Base
   belongs_to :user #-> for the original owner
   has_and_belongs_to_many :users
end

The above is a has_and_belongs_to_many association, which gives you the ability to add users to the article:

#config/routes.rb
resources :articles do
   match "users/:id", to: :users, via: [:post, :delete] #-> url.com/articles/:article_id/users/:id
end

#app/controllers/articles_controller.rb
class ArticlesController < ApplicationController
   def users
      @article = Article.find params[:article_id]
      @user    = User.find params[:id]
      if request.post?
         @article.users << @user
      elsif request.delete?
         @article.users.delete @user
      end
      #redirect somewhere
   end
end

This will allow you to use:

 <%= link_to "Add User", article_user_path(@article, @user), method: :post %>
 <%= link_to "remove User", article_user_path(@article, @user), method: :delete %>

Upvotes: 0

Michael Kohl
Michael Kohl

Reputation: 66837

So users can have many articles and each article can belong to several users? Sounds like a has_and_belongs_to_many relationship. Have a look at the relevant Rails documentation:

http://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association

In short you'd have a articles_users table, where each row consists of article_id and user_id. When adding a new users to an article, you just create another record in that table.

Alternatively you could look at has_many :through if you believe you'll work with that relationship as a separate entity. I.e. article has_many :users, through: authors.

http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association

To help you decide, the guide offers some advice:

http://guides.rubyonrails.org/association_basics.html#choosing-between-has-many-through-and-has-and-belongs-to-many

Upvotes: 1

Related Questions