Ruby on Rails - Get object association values with array of symbols

风格不统一 提交于 2019-12-10 10:43:10

问题


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.



来源:https://stackoverflow.com/questions/32469863/ruby-on-rails-get-object-association-values-with-array-of-symbols

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!