Dustin James
Dustin James

Reputation: 571

Rails dynamic link_to's

I have a view that has the following ruby code that I want to use to create a dynamic link in my application:

<% @customer.jobs.each do |job| %>
  <%= link_to job.id, job %>
<% end %>

This throws an undefined method error for job_path, which makes sense since my jobs_controller show method is empty:

def show
end

Here are my routes:

resources :customers do
  resources :jobs
end

My question is - how do I set up the method in the controller to make my link_to work on the view page?

Essentially, I am pulling an item from the DB, and then trying to create a link to the corresponding view using the DB item.

Any ideas?

Upvotes: 2

Views: 2559

Answers (3)

Mandeep
Mandeep

Reputation: 9173

You have

<%= link_to job.id, job %>

Here second option specifies your url or path helper. You are getting this error because there is no job_path helper for your routes

To check all the url or path helpers do rake routes in your terminal. It will give you output which looks something like

Prefix       Verb   URI Pattern                                     Controller#Action

customer_job GET    /customers/:customer_id/jobs/:id(.:format)      jobs#show

So replace your link with

<%= link_to job.id, customer_job_path(@customer,job) %> 

UPDATE:

Referring to your comment:

@customer is an instance variable of your Customer model which you would have defined in your controller action(since you are using it in your view). Instance variables defined in your controller action are automatically available for its view. For details you should read docs

Upvotes: 5

August
August

Reputation: 12558

You can use shallow resources

resources :customers, shallow: true do
  resources :jobs
end

and then use the job_path url helper:

<%= link_to job.id job_path(job) %>

Upvotes: 2

ob264
ob264

Reputation: 535

Run

rake routes

you will probably find that the route is actually something like customer_job_path

To work with this you will need to change the link_to to

  <%= link_to job.id, customer_job_path(@customer, job) %>

Upvotes: 1

Related Questions