views:

54

answers:

3

I don't know if this a Ruby question or a Rails question but in this example of a use of nested resources in Rails, how is it possible to assign an event object to an event_id? The event object would seem to represent a larger set of values than the event_id does.

<%= link_to 'Tickets', event_tickets_path(:event_id => @event) %>
+2  A: 

The following syntax should work:

event_tickets_path(@event)
Edwin V.
Actually, I suspect this will not work. The name "event_id" rather than "id" implies that this is a foreign key, perhaps on a join table, and I don't think Rails will deduce that an @event should be mapped to a particular foreign key - only to a primary key, thus the need for the ":event_id => @event" syntax... Please correct me if I am wrong.
SingleShot
+1  A: 

It is a convenience built into Rails. Behind the scenes it will figure out you really just want the id. See the documentation for link_to. Here's one of its examples:

link_to "Profile", :controller => "profiles", :action => "show", :id => @profile
# => <a href="/profiles/show/1">Profile</a>

Note that something similar is being done here, and that the resulting href is using the ID.

SingleShot
Thx for the link to the link_to docs.
i_like_monkeys
Two lines above the line that you quoted is:link_to "Profile", profile_path(@profile)As long as event is declared as a resource in your routes file, you should be able to use it in the way Edwin suggested below. It seems like the more RESTful version is generally preferred, since it's less brittle, so if it's simple to get working, I'd recommend that.
Kyle
A: 

In this context, Rails calls @event.to_param and returns the id attribute - to_param does this by default. You can override the to_param method in the Event Model to get it to return something other than the id.

It's not really assigning an event object to the event_id, it's assigning event.id.

Swards