Zeck
Zeck

Reputation: 6579

Rails: How to build an association dynamically

How can I build an association dynamically? For example:

current_customer.company.association(:tenders).order('created_at DESC')

Upvotes: 0

Views: 264

Answers (2)

digidigo
digidigo

Reputation: 2584

I am guessing that you want to pass in the association to some other method. What you are looking for there is the send(:method_name, *args)

so it would be

passed_in_association = :tenders
if( [:tenders,:orders,:users].include?(passed_in_association) )  #for security probably better to add it to a before filter.
 current_customer.company.send(passed_in_association).order('created_at DESC')
end

Upvotes: 2

Peter Duijnstee
Peter Duijnstee

Reputation: 3779

I'm not sure exactly what you're trying to do but you can just use send if you want to use a variable to access an association (it's just another method after all):

current_customer.company.send(:tenders).order('created_at DESC')

Upvotes: 1

Related Questions