Reputation: 3383
In my app, I have a view that shows a number of products. If a product has an active "deal" on it, a link to that deal is given for that deal that links to the show
action for that deal, as below.
<tr>
<% @item.inventory_items.each do |p| %>
<td><%= link_to image_tag("#{p.vendor.image_url}"), vendor_path(p.vendor) %></td>
<td class="price">$<%= p.price %></td>
<td>
<% if Deal.where(:product_code => p.product_code, :vendor_id => p.vendor_id).exists? %>
<%= link_to "See It!", deal_path(Deal.where(:product_code => p.product_code, :vendor_id => p.vendor_id)) %>
<% else %>
<% end %>
</td>
<td>
......
</td>
</tr>
The problem I'm having is that my show
action for Deal is looking in params for a deal id
. This deal id isn't really in params, so how can I tell this Deal show action which deal I'm interested in? Thanks in advance! As an aside, my above code feels really verbose and very un-rails-like in my if
block. If you have any suggestions for it, any advice is much appreciated.
deal/show.html.erb
<%= link_to image_tag("#{@deal.vendor.image}") %>
<%= @deal.vendor.address %>
<%= image_tag(@deal.image) %>
Deal show action:
def show
@deal = Deal.find(params[:id])
end
Upvotes: 0
Views: 99
Reputation: 19294
Your code is definitely not very rails-like.
What you should be able to do is something like this:
<tr>
<% @item.inventory_items.each do |p| %>
<td><%= link_to image_tag("#{p.vendor.image_url}"), vendor_path(p.vendor) %></td>
<td class="price">$<%= p.price %></td>
<td>
<% if p.deal.exists? %>
<%= link_to "See It!", deal_path(:id => p.deal.id)) %>
<% else %>
<% end %>
</td>
<td>
......
</td>
</tr>
Note that you can pass parameters along in a link_to. See this question - link_to send parameters along with the url and grab them on target page
If you're models are setup correctly, you shouldn't have to be doing queries in your views.
Upvotes: 2
Reputation: 3921
Try
<%= link_to "See It!", deal_path(Deal.where(:product_code => p.product_code, :vendor_id => p.vendor_id).first) %>
Upvotes: 2