Вопрос

Let's say I have some classes linked by a one-to-many relationship:

class A
  field :name, type: String
  has_many :b

class B
  field :title, type: String 
  belongs_to :a

Let's also say I have an instance of B and I want to retrieve the class name(s) of his belongs_to relationship (in my example 'A', not the instance of type A linked to my B object).

a = A.new name: 'my A object'
b = B.new title: 'my B object', a: a

assert_equal b.get_relationships(:belongs_to), ['A'] #substitute "get_relationships" with something that actually exists :)

What should I do?

I had a look at this answer on a similar topic (using reflection) but I couldn't manage to make it work. Maybe something has changed in Rails 4?

Это было полезно?

Решение

B.reflect_on_all_associations(:belongs_to).map(&:name)

or

b.class.reflect_on_all_associations(:belongs_to).map(&:name)
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top