Rails 4.2 has_many through in-place editing nested form with xeditable

263 views Asked by At

I have the following list of models in a Rails 4.2 app:

  • User
  • Company
  • Marketplace

The associations look like the following:

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

I am trying to build a form to allow adding/removing marketplaces to a company with the help of in-place editing library x-editable. I was able to allow adding new marketplaces from an existing list but it fails on the removing because no data is submitted.

This is the relevant part of the view:

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"

And companies_controller.rb#update method looks like the following:

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

Most of the resources I was able to find do not deal with in-place editing or use fields_for to work with nested_forms.

Is there a solution to handle adding/removing has_many: through: associated objects in a form without relying on fields_for?

Thanks

1

There are 1 answers

0
jpalumickas On

You can provide marketplaces_attributes in params.

Example from: 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'

Read more examples in that link above