加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails嵌套模型 – 删除关联

发布时间:2020-12-17 02:59:21 所属栏目:百科 来源:网络整理
导读:什么相当于%= f.hidden_??field:_destroy%为null而不是毁灭? (即我只是将它从协会中删除,但我不想破坏它). 一个示例情况是: class Foo ActiveRecord::Base has_many :bar,:dependent=:nullify,:autosave=true accepts_nested_attributes_for :bar,:reje
什么相当于<%= f.hidden_??field:_destroy%>为null而不是毁灭? (即我只是将它从协会中删除,但我不想破坏它).

一个示例情况是:

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 %>

解决方法

创建一个这样的方法:

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示例应用程序,以显示所有部分如何协同工作.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读