Need help building out a has_many :through association :: RoR

20 views
Skip to first unread message

Manuel Quintanilla

unread,
Nov 9, 2015, 11:21:28 PM11/9/15
to Ruby on Rails: Talk
***Note if you have a similar setup and would share - email me @ alloffi...@gmail.com***


I'm still fairly new to RoR and am having a bit of trouble understanding how to setup the contributions controller and the form in the view.

Objective:
1. user1 creates post - which belongs to user1 
2. user2 click request button to join the user1_post as a contributor ( @ post_show page )

3. user1 clicks accepts or declines request button ( @ post_show page link_to contribution_requests ( true : false ) )
4. user2 is now a contributor to user1_post ( @ post_show list contributors )
5. user1 can remove user2 as a contributor ( @ post_show page link_to contribution_requests ( true : false ) )

Got the has_many :through setup properly and have tested it in the console

contribution.rb

class Contribution < ActiveRecord::Base
  belongs_to :post
  belongs_to :user

  def accept
    self.accepted = true
  end
end

post.rb

class Post < ActiveRecord::Base
  belongs_to :author, class_name: 'User'
  has_many :contribution_requests, -> { where(accepted: false) }, class_name: 'Contribution'
  has_many :contributions, -> { where(accepted: true) }
  has_many :contributors, through: :contributions, source: :user
end

user.rb

class User < ActiveRecord::Base
  has_many :posts, foreign_key: 'author_id'
  has_many :contribution_requests, -> { where(accepted: false) }, class_name: 'Contribution'
  has_many :contributions, -> { where(accepted: true) }
  has_many :contributed_posts, through: :contributions, source: :post
end

contributions_controller.rb


#config/routes.rb
resources :posts do
   resources :contributions, only: [:create, :destroy] #-> can use posts#edit to add extra contributions
end

#app/controllers/contributions_controller.rb
class ContributionsController < ApplicationController
   def create
      @post = Post.find params[:post_id]
      @contribution = current_user.contributions.new contribution_params
      @contribution.post = @post

      notice = @contribution.save ? "Added Contributor" : "Unable to add contributor"
      redirect_to @post, notice: notice
   end

   def destroy
      @contribution = current_user.contributions.find params[:id]
      @contribution.destroy

      redirect_to root_url, notice: "Removed Contributor"
end

   private

   def contribution_params 
      params.require(:contribution).permit(:user, :post, :accepted)
   end
end




Reply all
Reply to author
Forward
0 new messages