Rails 4.2 has_many通过就地编辑嵌套表单和xeditable

时间:2015-06-17 10:54:56

标签: ruby-on-rails-4 form-submit frontend nested-forms x-editable

我在Rails 4.2应用中有以下模型列表:

  • 用户
  • 公司
  • 市场

协会如下所示:

User.rb

class User < ActiveRecord::Base
end

Company.rb

class Company < ActiveRecord::Base

  has_many :company_marketplaces
  has_many :marketplaces, through: :company_marketplaces

  accepts_nested_attributes_for :marketplaces, update_only: true
end

Marketplace.rb

class Marketplace < ActiveRecord::Base
  has_many :company_marketplaces
  has_many :companies, through: :company_marketplaces
end

我正在尝试使用就地编辑库x-editable构建表单以允许添加/删除市场到公司。我能够从现有列表中添加新市场,但在删除时失败,因为没有提交数据。

这是观点的相关部分:

index.html.slim

        td
          = link_to company.marketplaces.join(", "), "", data: { :"name" => "marketplaces_attributes" , :"xeditable" => "true", :"url" => admin_agents_company_path(company), :"pk" => company.id, :"model" => "company", :"type" => "checklist", :"placement" => "right", :"value" => company.marketplaces.join(", "), :"source" => "/marketplaces" }, class: "editable editable-click"

companies_controller.rb#update方法如下所示:

companies_controller.rb

def update
  respond_to do |format|
    if @company.update(company_params)
      format.html { redirect_to @company, notice: 'Company was successfully updated.' }
      format.json
      format.js
    else
      format.html { render :edit }
      format.json { render json: @company.errors, status: :unprocessable_entity }
      format.js
    end
  end
end

我能找到的大多数资源都不处理就地编辑或使用fields_for来处理nested_forms

是否有解决方案可以在不依赖has_many:的情况下处理表单中添加/删除 through: fields_for相关对象?

由于

1 个答案:

答案 0 :(得分:-1)

您可以在参数中提供 marketplaces_attributes

示例来自:http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

class Member < ActiveRecord::Base
  has_many :posts
  accepts_nested_attributes_for :posts
end

params = { member: {
  name: 'joe', posts_attributes: [
    { title: 'Kari, the awesome Ruby documentation browser!' },
    { title: 'The egalitarian assumption of the modern citizen' },
    { title: '', _destroy: '1' } # this will be ignored
  ]
}}

member = Member.create(params[:member])
member.posts.length # => 2
member.posts.first.title # => 'Kari, the awesome Ruby documentation browser!'
member.posts.second.title # => 'The egalitarian assumption of the modern citizen'

阅读上述链接中的更多示例