为什么更新表单重复我的表单字段并使用habtm和嵌套表单复制记录?

时间:2014-10-10 12:31:57

标签: ruby-on-rails ruby ruby-on-rails-4 nested-attributes has-and-belongs-to-many

我在父表单中有一个嵌套表单,允许您在父表单中添加字段。这个想法是,一本书可以有很多学校,学校属于书(habtm)的关系。这是我的模特:

books.rb

accepts_nested_attributes_for :author
accepts_nested_attributes_for :gallery, :allow_destroy => true
accepts_nested_attributes_for :schools, :reject_if => :find_school, :allow_destroy => true
accepts_nested_attributes_for :images, :allow_destroy => true


def find_school(school)
    if existing_school = School.find_by_school_name(school['school_name'])
       self.schools << existing_school
      return true
    else
      return false
    end
end

school.rb

class School < ActiveRecord::Base

    has_and_belongs_to_many :books

    validates :school_name, :address, presence: true
    #validates_uniqueness_of :school_name
end

在本书的表格中,我有这样的设置:

<div id="school" class="field">
      <h3>Schools reading this book (add the name and full address of the school)</h3>
      <%= f.simple_fields_for :schools, :wrapper => 'inline' do |builder| %>  
        <%= render 'school_fields', :f => builder %>
        <%= link_to_add_association 'add school', f, :schools, :render_options => {:wrapper => 'inline' }, :class => 'fa fa-plus' %>
      <% end %>
    </div>

在这里它应该渲染字段,但我得到了这个

the fields in the edit form after update

我遇到的问题是,在我的book.rb模型中,find_school方法在更新图书时会不断返回相同图书的多个值。我们的想法是,find_school方法基本上会阻止重复学校被创建为记录,而只是将它们分配为与书籍的关系。我发现更新的这个self.schools << existing_school只是在编辑表单中复制字段,并在检查params输出时将字段添加为项目的条目。

任何人都可以帮忙解决这个问题。

0 个答案:

没有答案