nullnullnull
nullnullnull

Reputation: 8189

Rails: Passing An Association As A Parameter

In my model, I have several associations, such as:

has_many :posts
has_many :comments, :through => :posts
belongs_to :user

I also have a method that I want to gather associated objects, as specified by a parameter:

def selected_associations(*associations)
  associations.collect{|association| self.association}
end

The thing is, how do I pass in *associations? I've tried doing so with an array of symbols:

self.selected_associations([:posts, :comments])

But that doesn't work. Neither does passing them in as strings. Perhaps I'm not approaching this the right way?

Upvotes: 0

Views: 458

Answers (1)

hahaha
hahaha

Reputation: 476

Two points here.

First of all, self.association won't work. You need change this to:

def selected_associations(*associations)
  associations.collect{|association| self.public_send(association)}
end

About method call, you need to pass as hash.

selected_associations :posts, :comments

Best.

Upvotes: 1

Related Questions