簡體   English   中英

Rails中關聯模型的父模型訪問ID

[英]Access ID of parent model from associated model in rails

好的,我在滑軌中有以下模型:

  • 碎片
  • 屬於分片或不屬於任何事物的“現實”
  • 屬於現實的“空間”
  • 屬於空間的“屬性”

我可以訪問shard.reality.space.first.properties,但我希望能夠通過屬性模型中的自定義方法訪問“ shard” ID(如果已通過這種方式進行訪問)。

有什么辦法嗎?

Property對象的實例方法中,這應該可以工作:

shard_id = space.reality.shard_id
# returns either the shard id, or nil if the reality doesn't belong to a shard
class Property < ActiveRecord::Base
  belongs_to :space

  def custom_method
    space.reality.shard.id if space.reality.shard
  end
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM