问题
Ok, my situation. I have a nested resource of
resources :projects do
resources :campaigns
end
I want to make a view with controller with
resources :portfolios
I want to make a <% link_to %> that listed all campaigns which I can do, but when I try to route the path i can't make it link to a campaign.
Example: in my portfolios/view/index.html.erb
<% @projects.each do |p| %>
<% p.campaigns.each do |c| %>
<div class="container" >
<div>
<%= link_to ( image_tag c.image_camp.url(:thumb)), p %>
</div>
<div class="col-md-2">
<h3 style=""><%=link_to c.title, p %></h3>
<h4><%= c.end_date %></h4>
<h4><%= c.project_end %></h4>
</div>
<div class="col-md-6">
<h4><%= c.project_end %></h4>
<p><%= link_to "read more", p %></p>
</div>
</div>
<% end %>
<% end %>
The above example links to the @project, I have tried putting 'c' in hopes it will link to the @campaign that I am obviously getting information from, but when I do I get the error
undefined method `campaign_path' for #<#<Class:0x0000000cc74b68>:0x0000000ef964c0>
I've also tried project_campaigns_path(@project, campaign) and every other combination I could think of.
undefined local variable or method `campaign' for #<#<Class:0x0000000cc74b68>:0x0000000ae94cd8>
I feel the problem lies in the portfolios_controller and that I have yet to understand how the controller affects routes and how to access those variables.
class PortfoliosController < ApplicationController
def index
@projects = Project.all.order('created_at DESC').includes(:campaigns)
end
end
I assumed that @projects and @campaigns are both found as I am able to display everything on the portfolio/view, what am I missing?
回答1:
You need to pass the Project
and the Campaign
to the link_to
. It will then know how to route to the nested resource.
来源:https://stackoverflow.com/questions/34096668/how-can-i-link-to-a-nested-child-from-outside-the-parent-element-in-rails-4