【问题标题】:Rails: has many relationship - determine which related object from within methodRails:有很多关系 - 从方法中确定哪个相关对象
【发布时间】:2013-01-22 01:22:03
【问题描述】:

我有两个类具有以下关系/方法:

class Bar
  has_many :foos

  def bar_method
    #puts the specific foo that called it
  end
end

class Foo
  belongs_to :bar

  def foo_method
    bar.bar_method
  end
end

当在 Foo 的实例上调用 foo_method 时,我如何知道是哪个 Foo 从 bar_method 中调用了它?这可能吗?

谢谢

【问题讨论】:

    标签: ruby-on-rails ruby has-many relationships


    【解决方案1】:

    是的!这是一个简单的方法;)

    class Bar
      has_many :foos
    
      def bar_method foo
        puts foo
      end
    end
    
    class Foo
      belongs_to :bar
    
      def foo_method
        bar.bar_method self
      end
    end
    

    【讨论】:

    • 感谢您的回复。我已经通过了自我,但看起来有点矫枉过正。想我会检查是否有任何方法可以自动推断它。再次感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-27
    • 1970-01-01
    • 1970-01-01
    • 2015-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多