Question

In Ruby on Rails I have a user models and a jobs model joined through a different model called applicants. I have a button for the users when they want to "remove their application for this job" but I don't know how to remove the specific user, and for that matter I don't know if I'm doing a good job at adding them either (I know atleast it works). user.rb

class User < ActiveRecord::Base
...
    has_many :applicants
    has_many:jobs, through: :applicants
end

job.rb

class Job < ActiveRecord::Base
...
  has_many :applicants
  has_many:users, through: :applicants
end

applicant.rb

class Applicant < ActiveRecord::Base
    belongs_to :job
    belongs_to :user
end

when someone applies for a job my jobs controller is called:

class JobsController < ApplicationController
...
def addapply 
    @job = Job.find(params[:id])
    applicant = Applicant.find_or_initialize_by(job_id: @job.id)
    applicant.update(user_id: current_user.id) 
    redirect_to @job
end
...
end

Does that .update indicate that whatever is there will be replaced? I'm not sure if I'm doing that right.

When someone wants to remove their application I want it to go to my jobs controller again but I'm not sure what def to make, maybe something like this?

def removeapply
    @job = Job.find(params[:id])
    applicant = Applicant.find_or_initialize_by(job_id: @job.id)
    applicant.update(user_id: current_user.id).destroy
    redirect_to @job
end 

does it ave to sort through the list of user_ids save them all to an array but the one I want to remove, delete the table then put them all back in? I'm unsure how this has_many works, let alone has_many :through sorry for the ignorance!

thanks!

Was it helpful?

Solution

Let's assume the user will want to remove their own application. You can do something like this:

class UsersController < ApplicationController
  def show
    @applicants = current_user.applicants # or @user.find(params[:id]), whatever you prefer
  end
end


class ApplicantsController < ApplicationController
  def destroy
    current_user.applications.find(params[:id]).destroy
    redirect_to :back # or whereever
  end
end

And in your view:

- @applicants.each do |applicant|
  = form_for applicant, method: :delete do |f|
    = f.submit

Don't forget to set a route:

resources :applicants, only: :destroy

Some observations, I would probably name the association application instead of applicant. So has_many :applications, class_name: 'Applicant'.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top