Sanyam Jain
Sanyam Jain

Reputation: 383

Passing model instance variable from one controller to another in redirect_to in Rails

I am using Rails version 3.2.10. I am trying to pass a model instance variable with many attributes in it from one action to another action in different controller.

I have tried many things, but not getting a solution.

First controller method:

def create
if current_user
  auth = request.env["omniauth.auth"]
  @applicant = Applicant.new
  if (auth['provider'] == "linkedin")
    puts auth.info.image
    linkedinProfileImport(auth)
    @applcant.first_name = auth.info.first_name
    @applcant.second_name = auth.info.last_name

   redirect_to controller => 'job_applicants', :action => 'newProfile' , :id => params[:id]
    end   

Second controller method:

 def newProfile
 @job = Job.find_by_id(params[:id])
 puts @job.id
 @applicant = Applicant.new
 @applicant = @applicant

end

I have to access the @ applicant variable from first controller into second controller method.

Upvotes: 1

Views: 3751

Answers (2)

Solomon
Solomon

Reputation: 7033

You should move a lot of this logic from the controller into the model.

So, I would have a model method:

def create #in the controller
  if current_user
    auth = request.env["omniauth.auth"]
    @applicant = Applicant.create_from_omniauth_hash(auth)

   redirect_to controller => 'job_applicants', :action => 'newProfile' , :id => params[:id]
end  



class Applicant < ActiveRecord::Base
  def self.create_from_omniauth_hash(auth)
    applicant = Applicant.new
    if (auth['provider'] == "linkedin")
      puts auth.info.image
      linkedinProfileImport(auth)
      applicant.first_name = auth.info.first_name
      applicant.second_name = auth.info.last_name
    end
    create_new_profile(applicant)
    applicant.save!
  end

  def create_new_profile(applicant)
    applicant.job = "job"
  end
end

Upvotes: 0

Raindal
Raindal

Reputation: 3237

You just can't do that... You will have to store your object in DB in the first action and then retrieve it in the second one.

With a redirect_to, you can pass arguments as you would in a url for example, not complete objects. Here you would pass the saved object id in the redirect_to.

Upvotes: 4

Related Questions