【问题标题】:Rails Nested Model - Remove AssociationRails 嵌套模型 - 删除关联
【发布时间】:2010-12-08 00:03:00
【问题描述】:

什么相当于<%= f.hidden_field :_destroy %> 用于无效而不是销毁? (即我只是要将它从关联中删除,但我不想破坏它)。

一个例子是:

class Foo < ActiveRecord::Base
  has_many :bar, :dependent=>:nullify, :autosave=>true
  accepts_nested_attributes_for :bar, :reject_if => proc { |attributes| attributes.all? {|k,v| v.blank?} }


class Bar < ActiveRecord::Base
  belongs_to :foo

在 Foo 的edit.html.erb:

<%= f.fields_for :bar do |builder| %>
   <%= builder.some_rails_helper %>
   <%= builder.hidden_field :_remove  #<-- set value to 1 to destroy, but how to unassociate?%> 
<% end %>

对解决方案的一个小修改

def remove
  #!self.foo_id.nil? should be:
  false #this way newly created objects aren't destroyed, and neither are existing ones.
end

所以现在我可以调用 .edit.html:

<%= builder.hidden_field :_remove %>

【问题讨论】:

    标签: ruby-on-rails nested-attributes


    【解决方案1】:

    创建一个这样的方法:

    class Bar
      def nullify!
        update_attribute :foo_id, nil
      end
    end
    

    现在您可以在任何 bar 实例上调用它。为了使其适合您的示例,您可以这样做:

    def remove
      !self.foo_id.nil?
    end
    
    def remove= bool
      update_attribute :foo_id, nil if bool
    end
    

    此版本将允许您传入一个等于 true 或 false 的参数,因此您可以将其实现为表单中的复选框。我希望这会有所帮助!

    更新:我添加了一篇博文,详细介绍了如何通过向模型添加访问器将非属性用作 Rails 中的表单元素:

    Dynamic Form Elements in Ruby on Rails

    它包括一个工作 Rails 3 示例应用程序,以展示所有部分如何协同工作。

    【讨论】:

    • 您先生,非常有帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多