Ruby on Rails - Get object association values with

2019-05-20 04:37发布

问题:

For example, have the models:

class Activity < ActiveRecord::Base
    belongs_to :event
end

class Event < ActiveRecord::Base
    has_many :activities
    attr_accessible :foo
end

I can get the activity's event foo by using activity.event.foo (simple enough).

But I want to make a generic function that finds out first if an object has a belongs_to association and then get that object's foo through the belongs_to association (pretend that all objects have a foo through the belongs_to association)?

So far I have the following with gives me a reflection:

def get_foo(object)
    object.class.reflect_on_all_associations(:belongs_to).each do |belongs_to|
        return object.??????
    end
end

I can either get an array of the reflection's class name via belongs_to.klass (e.g. [Event]) or an array of symbols for the belongs_to association via belongs_to.name (e.g. [:event]).

How do I get the object's belongs_to's foo given what I get from the reflection?

Is there an easier way to do this without using the reflection?

I'm hoping this is something simple and I'm just spacing out on how to solve this. I also hope I am being somewhat clear. This is my first Stack Overflow question.

回答1:

You can do this but its not exactly pretty:

def get_foo(object)
  object.class.reflect_on_all_associations(:belongs_to).map do |reflection|
    object.send(reflection.name).try(:foo)
  end
end

That will give you an array of all the foos associated with the object. You can change it to not do map and do a first or something.