首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >带有has_many的嵌套表单,其中包含现有记录

带有has_many的嵌套表单,其中包含现有记录
EN

Stack Overflow用户
提问于 2019-03-31 04:57:32
回答 1查看 101关注 0票数 0

在我的应用程序中,我有客户和联系人。客户可以有多个联系人,联系人可以有多个客户。它们通过CustomerContact表相关联。问题是,基于他们的电子邮件地址,数据库只能有一个唯一的联系人。

那是什么,我想创建一个表单,用户可以在其中输入客户信息和他们想要的联系人数量。我使用cocoon gem实现了这一点。现在的问题是,没有“选择现有联系人”,只有文本字段,其思想是,当提交表单时,系统可以通过现有的电子邮件地址查看系统中是否已经存在联系人,并且不仅将客户分配给该联系人,还可以更新现有的联系人信息。如果是新联系人,则只需在数据库中插入一个新联系人并将该联系人分配给客户即可。

很明显,这完全超出了正常的处理方式。你通常会进行某种查找,然后选择一个现有的联系人,但这不是老板想要的。

这是我遇到的问题

当我为数据库中已存在的联系人输入电子邮件地址时,Rails总是抛出错误“联系人电子邮件已经被占用”。“没问题,我想”,对于现有的联系人,我将在数据库中查找,并通过操作控制器中的params来创建联系人的id属性。所以我写了下面的代码:

代码语言:javascript
复制
# convert the params to a Hash so we can manuipulate them
myparams = customer_params.to_h

# if we have contacts we want to assign to the customer
if myparams['contacts_attributes']
  # loop through each contact they entered
  myparams['contacts_attributes'].each do |k,v|
    # see if the contact exists in the database and isn't being destroyed
    if Contact.exists?(email: v['email']) && v['_destroy'] != '1'
      # grab the contact information
      contact = Contact.where(email: v['email']).first
      # just a double check that we got the contact from the database
      if contact
        # create an id attribute for the contact
        myparams['contacts_attributes'][k]['id'] = contact.id
      end
    end
  end
end

“太美了!”或者我是这样想的。当我尝试保存联系人时,遇到以下错误:

代码语言:javascript
复制
Couldn't find Contact with ID=117 for Customer with ID=

显然,当我将参数传递给Customer#new方法时,Rails正在对CustomerContact表执行查找,试图访问Contacts表,这样它就可以获得联系人的信息。但是,由于这是一个新客户,因此该关联尚未建立,因为该客户尚未创建。

好的..。所以我有了这个想法

如果我从contact_attributes中删除现有联系人并直接创建customer_contacts关联会怎么样!因此,在myparams['customer_contacts_attributes'] = []发挥作用的地方:

代码语言:javascript
复制
# convert the params to a Hash so we can manuipulate them
myparams = customer_params.to_h
# so we can create a record on the customer_contacts association
# directly if the contact already exits
myparams['customer_contacts_attributes'] = []    

# if we have contacts we want to assign to the customer
if myparams['contacts_attributes']
  # loop through each contact they entered
  myparams['contacts_attributes'].each do |k,v|
    # see if the contact exists in the database and isn't being destroyed
    if Contact.exists?(email: v['email']) && v['_destroy'] != '1'
      # grab the contact information
      contact = Contact.where(email: v['email']).first
      # just a double check that we got the contact from the database
      if contact
        # removed the contact
        myparams['contacts_attributes'].delete(k)
        # create the `customer_contact` association directly
        myparams['customer_contacts_attributes'].push({'user_id': contact.id})
      end
    end
  end
end

还有..。成功了!嗯,一些什么。保存客户,分配数据库中已存在的联系人,并创建和分配新的联系人...那么问题出在哪里呢?好吧..。如果由于任何原因验证失败,并且页面被重新绘制,则用户输入的现有联系人将从表单中消失。

我请求帮助

所以我有一些工作,但我真的需要帮助。我需要它,以便如果验证失败,联系人显示在表单中。而且,很明显这不是最好的方法。我希望有人以前在rails中做过这样的事情,并且有更好的方法来实现它。

我的关联设置如下:

代码语言:javascript
复制
class CustomerContact < ApplicationRecord
  belongs_to :customer
  belongs_to :contact
end

class Customer < ApplicationRecord
  has_many :customer_contacts
  has_many :contacts, through: :customer_contacts

  accepts_nested_attributes_for :customer_contacts
  accepts_nested_attributes_for :contacts, allow_destroy: true
end

class Contact < ApplicationRecord
  has_many :customer_contacts
  has_many :customers, through: :customer_contacts
end

contact部分的设置如下所示,请注意,我在new和edit操作中都使用了它:

代码语言:javascript
复制
<table class="table table-striped">
  <thead>
  <tr>
    <th>Name</th>
    <th>Email</th>
    <th>Phone</th>
    <th>Department</th>
    <th>Manager</th>
    <th>
      <%= link_to_add_association f, :contacts, class: 'btn btn-primary', partial: 'contact_fields', data: {
          association_insertion_node: '.contact_fields', association_insertion_method: :append
      } do %>
          <i class="fas fa-plus"></i>
      <% end %>
    </th>
  </tr>
  </thead>
  <tbody class="contact_fields">
  <%= f.fields_for :contacts do |contact| %>
      <%= render 'projects/contact_fields', f: contact %>
  <% end %>
  </tbody>
</table>

contact_fields partial如下:

代码语言:javascript
复制
<tr class="nested-fields">
  <td>
    <%= f.text_field :fullname, class: 'form-control invoke-contacts-search contact-fullname' %>
  </td>
  <td>
    <%= f.text_field :email, class: 'form-control invoke-contacts-search contact-email' %>
  </td>
  <td>
    <%= f.text_field :phone, class: 'form-control contact-phone' %>
  </td>
  <td>
    <%= f.text_field :department, class: 'form-control contact-department' %>
  </td>
  <td>
    <%= f.text_field :manager, class: 'form-control contact-manager' %>
  </td>
  <td>
    <%= link_to_remove_association  f, class: 'btn btn-danger' do %>
        <i class="fas fa-trash-alt"></i>
    <% end %>
  </td>
</tr>

下面是控制器new和create操作

代码语言:javascript
复制
def new
  @customer = Customer.new
  4.times { @customer.contacts.build }
end

def create

# convert the params to a Hash so we can manuipulate them
myparams = customer_params.to_h
# so we can create a record on the customer_contacts association
# directly if the contact already exits
myparams['customer_contacts_attributes'] = []    

# if we have contacts we want to assign to the customer
if myparams['contacts_attributes']
  # loop through each contact they entered
  myparams['contacts_attributes'].each do |k,v|
    # see if the contact exists in the database and isn't being destroyed
    if Contact.exists?(email: v['email']) && v['_destroy'] != '1'
      # grab the contact information
      contact = Contact.where(email: v['email']).first
      # just a double check that we got the contact from the database
      if contact
        # removed the contact
        myparams['contacts_attributes'].delete(k)
        # create the `customer_contact` association directly
        myparams['customer_contacts_attributes'].push({'user_id': contact.id})
      end
    end
  end
end

  @customer = Customers.new(myparams)

  respond_to do |format|
    if @customer.save
      format.html { redirect_to edit_customer_path(@customer), success: 'Customer was successfully created.' }
    else
      format.html { render :new }
    end
  end
end

以下是控制器的编辑和更新操作

代码语言:javascript
复制
def edit
  @customer = Customer.find(params[:id])
end

def update
  myparams = customer_params.to_h

  if myparams['contacts_attributes']
    myparams['contacts_attributes'].each do |k,v|
      if Contacts.exists?(email: v['email']) && v['_destroy'] != '1'
        contact = Contact.where(email: v['email']).first
        if contact
          myparams['contacts_attributes'][k]['id'] = contact.id
          CustomerContact.find_or_create_by(project_id: @customer.id, user_id: contact.id)
        end
      end
    end
  end

  @customer.assign_attributes(myparams)

  respond_to do |format|
    if @customer.save
      format.html { redirect_to edit_customer_path(@customer), success: 'Customer was successfully updated.' }
    else
      format.html { render :edit }
    end
  end
end
EN

回答 1

Stack Overflow用户

发布于 2019-04-03 02:57:25

所以我终于让它工作了,但为了让它工作,我基本上必须重新实现嵌套属性为您做的所有事情。它不是很漂亮,但它工作得很好。

还有..。查看this post,看看我是如何在模板中收集联系人的

代码语言:javascript
复制
  def update

    myparams = customer_params.to_h
    contacts_valid = true
    @customer.assign_attributes(myparams)
    customer_valid = @customer.valid?
    @contacts = []
    contacts_to_delete = []

    cparams = contact_params.to_h
    cparams['contacts'].each do |k, v|
      if v['id'].to_i > 0
        if v['_destroy'].to_i == 1
          contacts_to_delete << v['id'].to_i
        else
          contact = Contact.find(v['id'])
          contact.assign_attributes(v.except('_destroy', 'id'))
        end
      else
        if (!v['name'].blank? || !v['email'].blank?) && v['_destroy'].to_i != 1
          unless v['email'].blank?
            contact = Contact.where(email: v['email']).first
          end
          if contact
            contact.assign_attributes(v.except('_destroy', 'id'))
          else
            contact = Contact.new(v.except('_destroy', 'id'))
          end
        end
      end

      if contact
        unless contact.valid?
          contacts_valid = false
          # This adds the errors from the contact to the customer object
          contact.errors.full_messages.each do |m|
            @customer.errors.add(:base, m)
          end
        end
        @contacts << contact
      end
    end

    respond_to do |format|
      if customer_valid && contacts_valid
        @customer.save!
        @contacts.each do |c|
          c.save!
          CustomerContact.find_or_create_by(customer_id: @customer.id, contact_id: c.id)
        end
        CustomerContact.where(customer_id: @customer.id, contact_id: contacts_to_delete).destroy_all

        format.html { redirect_to edit_customer_path(@customer), success: 'Customer was successfully updated.' }
        format.json { render :show, status: :ok, location: @customer }
      else
        format.html {
          (6 - @contacts.count).times { @contacts << @customer.contacts.build }
          render :edit
        }
        format.json { render json: @customer.errors, status: :unprocessable_entity }
      end
    end

  end

  def customer_params
    params.require(:customer).permit(:company, :name, :line1, :line2, :city, :state, :zipcode, :country, :webaddress, :status,
                                     contacts_attributes: [:fullname, :phone, :email, :department, :manager, :id, :_destroy],
                                     notes_attributes: [:note]
    )
  end

  def contact_params
    params.permit(contacts: [:fullname, :email, :phone, :department, :manager, :id, :_destroy])
  end
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55435600

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档