简体   繁体   中英

Passing object ID across models Rails

I am trying to create an app that allows users to create and apply for jobs but seem to have hit a problem.

I can't get the job_id to pass into my apps (job applications) table in my database.

To get this app to work succesfully I need to pass the job_id and the user_id to the user's application form so that when they submit their job application this information is stored in my apps table. The job owner will then be able to review the applications they have received.

I have the following associations in my models:

 class App < ActiveRecord::Base
 belongs_to :job
 belongs_to :user

 class Job < ActiveRecord::Base
 belongs_to :user
 has_many :apps
 has_many :applicants, :through => :apps, :source => :user

 class User < ActiveRecord::Base
 has_many :apps
 has_many :jobs
 has_many :jobs_applied_for, :through => :apps, :source => :job

Defined on my Jobs controller's show page (the page from which the user can click "apply now" to start an application) I have the following:

def show
  @job = Job.find(params[:id])    
end

The link to "apply now" on the actual page is:

<%=link_to "Apply Now", new_app_path %>

and on my Apps controller's new page I have:

def new
  @user = current_user
  @app = @user.apps.build
end

My user_id is passing perfectly and appearing in my apps table but I am totally stumped on how to pass the job_id correctly.

If I have missed anything that I can edit into this question to help you answer it then please do let me know.

Thanks in advance for your help!

You are not passing the job_id in your new_app_path link. Try changing it to new_app_path(:job_id => @job.id) , and in your controller add @job = Job.find(params[:job_id])

Assuming your routes nest apps inside jobs, your link to the new application page should be something like

link_to 'apply now', new_app_job_path(@job)

In your new action you'll have a params[:job_id] that you can use to set @job

Then on the form, your call to form for should look like

form_for [@job, @app] do |f|
  ...

This ensures that your create action will also have a :job_id parameter that you can use when creating the application

The action that you should be invoking is create not new .

Change the link_to code as follows:

<%=link_to "Apply Now", apps_path(:app => {:job_id => @job.id}), :method => :post %>

In your controller:

def create
  app = current_user.apps.build(params[:app])
  if app.save
    # handle success
  else
    # handle error
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM