weixin_39782500 2020-11-22 01:59
浏览 0

Assigning a parent id to a child should load the parent resource/do something

This came about as an observed violation of principle of least surprise (on the basis that I saw someone in the process of being surprised). I explained that it was not necessary to load a parent resource to create a new child, because you can just do Child.create(:parent_id => parent_id).

To me, there's something not quite right here. What if this new child makes the parent invalid? Then there's a back-door to making a resource invalid.

WDYT about making setting parent ids load the parent resource? Is that a good idea? Could there be any problems? Is there another way of making the behaviour less surprising?

Created by Ashley Moran - 2009-07-19 13:30:56 UTC

Original Lighthouse ticket: http://datamapper.lighthouseapp.com/projects/20609/tickets/982

该提问来源于开源项目:datamapper/dm-core

  • 写回答

7条回答 默认 最新

  • weixin_39782500 2020-11-22 01:59
    关注

    : This is a good question.

    There’s also a flip side to this, maybe there are children that are only valid if the parent is in a given state, so modifying the parent and then saving it would cause some of it’s children to become invalid.

    In general I don’t recommend ever referencing the FK directly in creation statements or in queries. It tightly couples the code to database-like storage engines, which I realize is not a huge problem for most people, but the intention with DM is to provide ways to avoid code that is tightly coupled with one set of adapters. I would write this as: Child.create(:parent => parent), or even better parent.children.create.

    With that said, I don’t know the answer to your questions. I am sure there are cases where just updating a child could cause the parent to become invalid, or maybe the grandparent or even great-grandparent, etc.

    Maybe there needs to be a way for a model to communicate validation rules across a relationship that apply to target resources? It’s an edge case for sure, but off the top of my head I can’t think another way to do it without risking loading up the entire object graph.

    by Dan Kubb (dkubb)

    评论

报告相同问题?