Ruby on Rails - 获取对象与数组符号的关联值 [英] Ruby on Rails - Get object association values with array of symbols

查看:204
本文介绍了Ruby on Rails - 获取对象与数组符号的关联值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,有以下模型:

class Activity < ActiveRecord::Base
    belongs_to :event
end

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

我可以通过使用activity.event.foo(足够简单)获得活动的事件foo。

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

但我想创建一个通用函数,对象有一个belongs_to关联,然后通过belongs_to关联获取该对象的foo(假装所有对象都有一个foo通过belongs_to关联)?

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



我可以得到一个反射类名的数组通过belongs_to.klass(例如[Event])或者belongs_to关联的符号数组通过belongs_to.name(eg [:event])。

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]).

如何从反射中获得对象的belongs_to的foo?

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?

我希望这是一个简单的,我只是间距如何解决这个问题。我也希望我有点清楚。这是我第一个Stack Overflow的问题。

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.

推荐答案

你可以这样做,但不完全漂亮:

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

这将给你一个与该对象相关联的所有foos的数组。您可以将其更改为不执行 map 并先执行 或某事。

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.

这篇关于Ruby on Rails - 获取对象与数组符号的关联值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆