Pass a value through a link in Rails

I was trying to use the link_to method and it was giving an error

missing required keys: [:id]

I was trying to link_to a Supplier model from the PurchaseOrder index like this:
views/purchase_orders/index.html.erb

<%= link_to purchase_order.items[0].suppliers[0].name, supplier_path %></td>

Yes I know it looks convoluted – I have a somewhat complex database structure with several :has_many :through models that are nested and using accepts_nested_attributes_for

Anyway, I figured out via this Stack Overflow question that its actually quite easy to simply pass a value through the supplier_path like this:

supplier_path(:id => purchase_order.items[0].suppliers[0].id)

which gives my full link_to method as:

<%= link_to purchase_order.items[0].suppliers[0].name, supplier_path(:id => purchase_order.items[0].suppliers[0].id) %>

Don’t be confused by my convoluted code, essentially a simpler form would be:

<%= link_to purchase_order.name, supplier_path(:id => purchase_order.suppliers[0].id) %>

Hope this is helpful!

Advertisements

One Response to Pass a value through a link in Rails

  1. Pingback: What I learned today | Pass a value through a link in Rails

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: