Ruby on rails 我可以在非嵌套形式中使用_destroy属性吗?
假设我的控制器中有类似的东西:Ruby on rails 我可以在非嵌套形式中使用_destroy属性吗?,ruby-on-rails,Ruby On Rails,假设我的控制器中有类似的东西: FacultyMembership.update(params[:faculty_memberships].keys, params[:faculty_memberships].values) 只要params[:faculty\u memberships]值中的_destroy键为true,记录就会被销毁 rails中有类似的东西吗?我意识到还有其他方法可以做到这一点,我只是好奇这样的事情是否存在。简短回答 不
FacultyMembership.update(params[:faculty_memberships].keys,
params[:faculty_memberships].values)
只要params[:faculty\u memberships]值中的_destroy键为true,记录就会被销毁
rails中有类似的东西吗?我意识到还有其他方法可以做到这一点,我只是好奇这样的事情是否存在。简短回答
不
长话短说
还是不行!的确,它在以下方面起作用:
如果要通过属性销毁关联的模型
散列,您必须首先使用:allow\u destroy选项启用它。
现在,当您将_destroy键添加到属性散列时
值,则将销毁关联的模型
但是为什么不在控制台中尝试呢:
?> bundle exec rails c
?> m = MyModel.create attr_1: "some_value", attr_2: "some_value"
?> m.update(_destroy: '1') # or _destroy: true
?> ActiveRecord::UnknownAttributeError: unknown attribute '_destroy' for MyModel
这是因为实施如下:
# File activerecord/lib/active_record/persistence.rb, line 245
def update(attributes)
# The following transaction covers any possible database side-effects of the
# attributes assignment. For example, setting the IDs of a child collection.
with_transaction_returning_status do
assign_attributes(attributes)
save
end
end
其来源是:
这个代码对我有用:
class FacultyMembership < ApplicationRecord
attr_accessor :_destroy
def _destroy= value
self.destroy if value.present?
end
end
这可能会破坏destroy-未检查的嵌套表单。很好。在我看来,这将是一个非常漂亮的特性。Rails完全是关于REST的。因此,如果要删除一条记录,您将使用该记录映射到控制器的销毁方法。这就是为什么!
class FacultyMembership < ApplicationRecord
attr_accessor :_destroy
def _destroy= value
self.destroy if value.present?
end
end