简体   繁体   中英

How to find parent from child scope in rails?

Not entirely sure how to word my need properly. Code reflects it better:

class Product < ActiveRecord::Base
  def self.know_your_parent
    p ? # <------- is it possible to get order.id here?
  end
end

class Order < ActiveRecord::Base
  has_many :products
end

(order=Account.new).assign_attributes({id: 4}, without_protection: true)
order.products.know_your_parent # => "4"

In your example order.products.know_your_parent , know_your_parent function is called on the Array So if you can extend the array adding the function, you should be able to do it. But I'm not sure it is recommended to extend and use it that way.

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