【问题标题】:Rails 3 - How can I visit parent's attributes in belong_to/has_many relationship?Rails 3 - 我如何访问 belongs_to/has_many 关系中的父母属性?
【发布时间】:2012-12-13 22:45:44
【问题描述】:

我在 Rails 3 模型中有一个简单的问题: 以下是我拥有的模型:

  class Order < ActiveRecord::Base
      attr_accessible :customer :date #blahblah..
      has_many :items
      accepts_nested_attributes_for :items



  class Item < ActiveRecord::Base
      belongs_to :order

那么如何在我的程序中联系@item.customer

谢谢

【问题讨论】:

    标签: ruby-on-rails-3 activerecord model associations belongs-to


    【解决方案1】:

    通过order 关联本身。

    @item.order.customer
    

    如果您想有一种方便的方法直接从Item 对象访问customer,那么您必须编写一些自定义访问器方法。

    class Item < ActiveRecord::Base
    
      ...
    
      def customer
        self.order.customer
      end
    
      def customer=(new_customer)
        self.order.customer = (new_customer)
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-31
      • 2014-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多