简体   繁体   中英

Rails 3 accessing parent of child record

class A
 has_many :c

class B
 has_many :c

class C
 belongs_to :a
 belongs_to :b

When I have an instance of C , its parent can be either A or B but I don't know ahead of time which it is. Is there a simple way I can use Rails association to access the parent whichever it happens to be?

There are several ways you could do this, including polymorphism, but perhaps the most straightforward way is this:

class C
  belongs_to :a
  belongs_to :b

  def parent
    a || b
  end
end

# Usage:
C.new.parent # => nil

a1 = A.new
c1 = a1.c.create
c1.parent    # => #<A:...>

b1 = B.new
c2 = b1.c.create
c2.parent    # => #<B:...>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM