Friday, 15 April 2011

ruby on rails - How do I pass an activerecord association as a string to a method? -



ruby on rails - How do I pass an activerecord association as a string to a method? -

given next associations:

user has_many ultimate_source

user has_many budget_source

how create next method:

def foo(source) user = user.find(1) user.source.id end

such

foo(ultimate_sources)

returns:

user.ultimate_sources.id

thanks.

if source == :ultimate_sources or source == :budget_sources next should work.

user.send(source).id

if source string can convert symbol using source.to_sym.

the send method takes symbol representing name of method , sends message object execute method , homecoming method returns.

http://ruby-doc.org/core-2.1.2/object.html#method-i-send

ruby-on-rails activerecord

No comments:

Post a Comment