Tom Pinchen
Tom Pinchen

Reputation: 2497

Nested resource issue

I am struggling to pass an id successfully into my URL for the nested resource I have set up called Jobs.

The error I am getting when I try to pass the @job object into my link is as follows:

  No route matches {:action=>"edit", :controller=>"jobs", :user_id=>1, :id=>nil}

Which clearly shows it can't find the id correctly and so is finding nil

At the moment I have my routes setup as so:

 resources :users do
   resources :jobs
 end

and the link I have is <%= link_to "Edit", edit_user_job_path(@user.id,@job) %>

What is interesting is that if I pass the object @jobs with an 's' on the end it will load the page correctly but when I click on the link will try and add all of that users job id's.

In my controller for edit I have:

def edit
 @user = current_user
 @job = @user.jobs.find(params[:id])
end

Any help really would be much appreciated :)

UPDATE

Okay I was defining the object on the wrong page of my controller (under edit instead of index). The issue I am now having is Couldn't find Job without an ID

I updated my controller index definition to:

 def index
  @user = current_user
  @jobs = @user.jobs.all
  @job = @user.jobs.find(params[:id])
 end

And have in my view (jobs#index)

<% @jobs.each do |f| %>
 ...
 <%= link_to "Edit", edit_user_job_path(@user.id,job) %>
 ...
<% end %>

Any advice would be much appreciated if you know where I am going wrong :)

Upvotes: 0

Views: 122

Answers (2)

niels
niels

Reputation: 1739

(expanding on iHiD's comment with his own post)

Using the restful resources means that you are going with the rails defaults, which consequently means that the index page gives you a list of all Jobs, and by default no single special job. If you run rake routes from the command line, you get all the routes, with parameters that are set from the URI. It should give you something like this:

user_jobs GET    /users/:user_id/jobs(.:format)          jobs#index

As you can see, there is no :id (params[:id]) for the index action.

Upvotes: 1

iHiD
iHiD

Reputation: 2438

That error means that @job is nil.

The link is to the edit path, and the controller code you've provided is from the edit action in the controller. It seems unlikely that the edit page links to itself.

Look at the code that's actually rendering that page (it will appear in your stack trace) and you'll find that @job is not set. I suspect that you are on the index page and have something like:

<% @jobs.each do |job| %>
  ...
  <%= link_to "Edit", edit_user_job_path(@user.id,@job) %>
  ...
<% end %>

If that is the case, then the link should be to job, not @job, i.e.

<%= link_to "Edit", edit_user_job_path(@user.id,job) %>

Upvotes: 2

Related Questions