【问题标题】:RESTfully destroy polymorphic association in Rails?RESTfully 破坏 Rails 中的多态关联?
【发布时间】:2010-02-10 02:43:36
【问题描述】:

我如何销毁关联本身并保留关联的对象,同时保持此 RESTful?

具体来说,我有这些模型:

class Event < ActiveRecord::Base
  has_many :model_surveys, :as => :surveyable, :dependent => :destroy, :include => :survey
  has_many :surveys, :through => :model_surveys
end

class ModelSurvey < ActiveRecord::Base
  belongs_to :survey
  belongs_to :surveyable, :polymorphic => true
end

class Survey < ActiveRecord::Base
  has_many :model_surveys
end

也就是说,事件是:surveyable (ModelSurvey belongs_to Event)。我的问题是,无需创建ModelSurveysController,我如何销毁ModelSurvey,同时保留Event 和Survey?

map.resources :events, :has_many =&gt; :model_surveys 的东西?我不太确定在这种情况下该怎么做。路由需要做什么,控制器需要做什么?我希望网址看起来像这样:

/events/:title/model_surveys/:id

感谢您的帮助, 兰斯

【问题讨论】:

    标签: ruby-on-rails rest polymorphic-associations destroy


    【解决方案1】:

    在 Rails 2.3 中,您有 accepts_nested_attributes_for,它可以让您将一组 ModelSurveys 传递给相关事件。如果您允许通过嵌套属性声明进行破坏,您将能够传递 event[model_surveys][1][_destroy]=1 并且关联将被删除。查看api docs。

    【讨论】:

      【解决方案2】:

      资源域!= 模型域


      控制器的域与模型的域不同。通过更改资源的状态来更新多个模型是非常好的。

      在您的情况下,这意味着对事件或调查执行 PUT 或 POST,其中包含另一个 ID 列表。 one 的模型将更新关联。

      PUT 或 POST

      有些人(但不是Roy Fielding)认为您应该使用 PUT 来更新资源并再次提供所有状态,其他人则认为带有部分状态(ala PATCH)的 POST 就足够了。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-07-26
        • 2017-03-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多