英文:
How to access a many-to-many join model attribute for a not persisted record?
问题
Here's the translation of the code-related portion:
给定以下的结构,其中一个 `Step` 拥有多个 `Items`,而一个 `Item` 拥有多个嵌套的 `Items`:
class Step
has_many :step_items
has_many :items, through: :step_items
end
class Item
has_one :step_item
has_one :step, through: :step_item
has_many :nested_items, foreign_key: :parent_item_id
has_many :items, through: :nested_items
end
class StepItem
belongs_to :step
belongs_to :item
end
class NestedItem
belongs_to :parent_item, foreign_key: :parent_item_id
belongs_to :item
end
在构建嵌套的 `Items` 时,如何访问关联模型呢?
例如,对于与 `Step` 相关的 `Item`,可以像这样检索 `StepItem`:
```ruby
step.items.build.step_item # => StepItem
那么在构建项目时,如何访问特定的 NestedItem
模型呢?
item = step.items.build.items.build # => Item
item.??? # 如何检索连接 `item` 与其父级的 `NestedItem`?
请注意,这里的 "???" 表示您需要填入相应的代码来检索 `NestedItem` 模型。
<details>
<summary>英文:</summary>
Given the following structure where a `Step` has many `Items` and an `Item` has many nested `Items`:
class Step
has_many :step_items
has_many :items, through: :step_items
end
class Item
has_one :step_item
has_one :step, through: :step_item
has_many :nested_items, foreign_key: :parent_item_id
has_many :items, through: :nested_items
end
class StepItem
belongs_to :step
belongs_to :item
end
class NestedItem
belongs_to :parent_item, foreign_key: :parent_item_id
belongs_to :item
end
How could I access the join model when "building" nested `Items`?
For example, for an `Item` that was related to a `Step` I could retrieve the `StepItem` like this:
step.items.build.step_item # => StepItem
How would I access the specific instance of the `NestedItem` model when building items:
item = step.items.build.items.build # => Item
item.??? # How do I retrieve the NestedItem
that joins item
to it's parent?
</details>
# 答案1
**得分**: 1
Your terminology is a little off, so I'm not quite sure what you're asking:
例如,对于与步骤相关的项目,我可以这样检索StepItem:
step.items.build.step_item # => StepItem
这不是检索项目,而是创建一个新项目。但我认为你想要的是:
parent_item = step.items.build
item = parent_item.items.build # => Item
parent_item.nested_items.find{|ne| ne.item == item}
但你可能真正想要的是从项目到parent_item展开收缩的关系。
真正的问题可能是为什么你想要访问nested_item,因为它已经完成了它的整个工作。
<details>
<summary>英文:</summary>
Your terminology is a little off, so I'm not quite sure what you're asking:
For example, for an Item that was related to a Step I could retrieve the StepItem like this:
step.items.build.step_item # => StepItem
That's not retrieving an item, that's building a new one. But I *think* what you want is
parent_item = step.items.build
item = parent_item.items.build # => Item
parent_item.nested_items.find{|ne| ne.item == item}
But you may really want a relationship from Item to parent_item展开收缩.
The real question may be why you want to get at the nested_item at all since it has done its whole job already.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论