【问题标题】:Rails - Saving a new data from other moduleRails - 从其他模块保存新数据
【发布时间】:2014-10-10 11:12:31
【问题描述】:

我有Client 模型和Contact 模型。在客户端页面上,我将“添加到联系人”按钮保存在contact 模型上。

我的客户页面上有这段代码:

= form_for(@contact, remote: true, html: { class: 'form-horizontal ajax-form add-to-contact', style: 'margin-bottom: 0;', 'data-model-name' => 'contact'}) do |f|
  = f.text_field :type, :value => 'clients'
  = f.text_field :client_id, :value => client.id
  = f.submit "Add to Contact", class: 'btn btn-success btn-submit-add-to-contact'

clients_controler.rb

def index
  @contact = Contact.new(params[:client_id], params[:type])
end

contacts_controller.rb

def create
  @contact = Contact.new(contact_params)
    respond_to do |format|
      if @contact.save
        format.js {}
      else
        format.json { render json: @contact.errors, status: :unprocessable_entity }
      end
    end
end

而且我有咖啡文件代码,当我提交它时,它会保存到contact 模型:

  $(document).on "click", ".btn-submit-add-to-contact", ->
    $(this).prop "disabled", true
    $(this).val "Added to Contacts!"
    $(".add-to-contact").submit()

但是保存有问题。我所有的客户都保存了,因为尽管我没有提交其他客户,但它们正在循环并自动保存。请帮忙。

【问题讨论】:

  • 我们需要更多详细信息,因为我们无法确定问题所在。 all of my clients save 是什么意思 - 你在日志中看到了吗?简而言之,预计会发生什么以及正在发生什么?
  • 是的。我看到他们一直在节省。
  • 能否提供日志?
  • @BartSabayton 您如何在表单中获取 client.id,我看不到 client 的任何参数

标签: ruby-on-rails ruby coffeescript


【解决方案1】:

如果您要添加自己的 Ajax 功能,则应删除 remote: true。 此外,您应该阻止默认点击操作,否则浏览器将提交两次表单。

$(document).on "click", ".btn-submit-add-to-contact", ->(e)
    $(this).prop "disabled", true
    $(this).val "Added to Contacts!"
    $(".add-to-contact").submit()
    e.preventDefault()

如果您使用的是 jquery-ujs,则应改为监听已完成的 ajax 调用:

$(document).ready ->
  $("form").on("ajax:success", (e, data, status, xhr) ->

【讨论】:

    【解决方案2】:

    我知道了。

    我已经修改了我的 JS:

      $(document).on "click", ".btn-submit-add-to-contact", ->
        $(this).prop "disabled", true
        $(this).val "Added to Contacts!"
        contact_form = $(this).closest('.add-to-contact-form').find('.ajax-form')
        contact_form.submit()
        return
    

    我把课程放在表格之前:

    .add-to-contact-form
        = form_for(@contact, remote: true, html: { class: 'form-horizontal ajax-form add-to-contact', style: 'margin-bottom: 0;', 'data-model-name' => 'contact'}) do |f|
          = f.text_field :type, :value => 'clients'
          = f.text_field :client_id, :value => client.id
          = f.submit "Add to Contact", class: 'btn btn-success btn-submit-add-to-contact'
    

    我使用.closest,它对我来说很好用。 谢谢你帮助我!

    【讨论】:

      猜你喜欢
      • 2021-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      相关资源
      最近更新 更多