Stuck Understanding Link_to
I'm really struggling to understand how to link_to a parent from with a loop.
My milestones belong_to my orders and my orders have many milestones.
In my orders index, I have a simple calendar (table_builder) which lists all my milestones.
<%= calendar_for @milestones, :year => @date.year, :month => @date.month do |t| %>
<%#= 开发者_如何学Gocalendar_for(@orders, :year => 2009, :month => 1) do |t| %>
<%= t.head('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday') %>
<%= t.day(:day_method => :milestone_due) do |date, orders| %>
<%= date.day %>
<ul>
<% for milestone in orders %>
<li><%= link_to milestone.name, order_path %> </li>
<% end %>
</ul>
<% end %>
<% end %>
This all works swimmingly well but the link doesn't work - I need it to link back to the parent order, not the milestone. It's driving me crazy now!
In my controller, I tried putting:
@milestoneorder = Order.find(params[:id])
But that says it can't find an order without an id.
I'm obviously missing something really basic here.
You need to tell order_path
which Order
to link back to:
<%= link_to milestone.name, order_path(milestone.order) %>
You could probably just shorten it to this too:
<%= link_to milestone.name, milestone.order %>
UPDATE
If there's a chance some of your milestones don't have orders, you can try something like this:
<% if milestone.order %>
<%= link_to milestone.name, order_path(milestone.order) %>
<% else %>
<%= milestone.name %>
<% end %>
It doesn't sound like you have a route setup for order.
In the routes.rb
file
resources :orders
or if you do, you aren't passing in an id
for the order.
link_to "link text", order_url(:id => @order)
link_to "link text", order_url(@order) # <== shortened
lastly, the problem may be that order is nil. If it is nil, you will also get the 'can't find route' error.
UPDATE
<% orders.each do |order| %>
<li><%= link_to milestone.name, order_path(order) %> </li>
<% end %>
UPDATE 2
The problem is in the names. I think that you are getting get milestones from t.day not orders.
<%= t.day(:day_method => :milestone_due) do |date, milestones| %>
<%= date.day %>
<ul>
<% for milestone in milestones %>
<li><%= link_to milestone.name, order_path(:id => milestone.order_id) %> </li>
<% end %>
</ul>
<% end %>
精彩评论