Reputation: 820
I have a partial that has been passed an association. I want to get the object that passed me the association. How do I do this? I thought it would be easy but I cannot seem to find the method.
Here is what I pass to the partial:
<%= render :partial => 'shared/records_table', :locals => {:parent => @location, :records => @location.people} %>
Here is what I would like to pass to the partial:
<%= render :partial => 'shared/records_table', :locals => {:records => @location.people} %>
There are also instances like this:
<%= render :partial => 'shared/records_table', :locals => {:parent => @time, :records => @time.families} %>
And:
<%= render :partial => 'shared/records_table', :locals => {:parent => @car, :records => @car.families} %>
I do not know the class of the association or the parent.
Upvotes: 4
Views: 1930
Reputation: 871
Ran into something similar and the following worked. The ActiveRecord::Association
has a method to return the owner.
@foo.bars.proxy_association.owner
=> @foo
Upvotes: 2
Reputation: 1466
I would imagine in your Location class you have something like has_many :people
, and your Person class has something like belongs_to :location
. So why not just alias #parent
to the parent of each class. Your Person class would then look like:
belongs_to :location
alias_method :parent, :location
That way all your records will respond to parent and you won't need to pass it in to the partial. You'd need to do something similar in your Family class.
A caveat on this is that calling parent
in the partial will load the parent from the database for each record. When rendering your partial you would need to do something like this to avoid that:
render :partial => 'shared/records_table', :locals => {:records => @location.people.includes(:location)}
Upvotes: 0
Reputation: 4807
Not sure why you're opposed to just passing that information into the partial, but if location has many people and person belongs to location, then you can just take any of the people in that partial and call location to get the parent.
edit: Add a parent
method on your models that returns the appropriate association. For example person.parent
would return a Location
object.
Seriously though, there's nothing wrong with just passing the parent into the partial.
Upvotes: 0