Uziel Trujillo
Uziel Trujillo

Reputation: 47

store text_field in rails separate by comma in many to many assosiation

I have this models to store text_field in rails separate by comma in many to many assosiation.

class PaymentSupplier < ActiveRecord::Base
    has_many :folio_has_payment_suppliers
    has_many :folios, through: :folio_has_payment_suppliers, dependent: :destroy

    serialize :folio_ids, Array

    def folio_ids=(ids)
      self.folio_ids = ids.split(',')
    end
end

folio_has_payment_supplier.rb

class FolioHasPaymentSupplier < ActiveRecord::Base
  belongs_to :folio
  belongs_to :payment_supplier
end

folio.rb

class Folio < ActiveRecord::Base
  has_many :folio_has_payment_suppliers
  has_many :payment_suppliers, through: :folio_has_payment_suppliers, dependent: :destroy
end

And my partial form for payment_supplier#_form.html.erb my code for text_field separate by comma is

<%= f.text_field :folio_ids, :class => 'form-control' %>

When i submit my application frezee, this is my log

  app/models/payment_supplier.rb:11:in `folio_ids='
  app/models/payment_supplier.rb:11:in `folio_ids='
  app/models/payment_supplier.rb:11:in `folio_ids='
  app/models/payment_supplier.rb:11:in `folio_ids='
  app/models/payment_supplier.rb:11:in `folio_ids='
  app/models/payment_supplier.rb:11:in `folio_ids='
  app/models/payment_supplier.rb:11:in `folio_ids='
  app/models/payment_supplier.rb:11:in `folio_ids='
  app/models/payment_supplier.rb:11:in `folio_ids='
  app/models/payment_supplier.rb:11:in `folio_ids='
  app/models/payment_supplier.rb:11:in `folio_ids='
  app/controllers/egr/payment_suppliers_controller.rb:16:in `create'

Any idea please? Thanks in advance.

Upvotes: 0

Views: 201

Answers (1)

shayonj
shayonj

Reputation: 910

The reason you are getting this is because the field assignment goes into a infinite loop with self association. You can use an attr_accessor to get the user entered information into a Serialized (Array) column.

It would look something like this:

PaymentSupplier

class PaymentSupplier < ActiveRecord::Base
    ...

    serialize :folio_ids, Array
    attr_accessor :folio_ids_text

    def folio_ids_text=(ids)
      self.folio_ids = ids.split(",").map(&:strip) # added map(&:strip)
    end
end

form

<%= f.text_field :folio_ids_text, :class => 'form-control' %>

Make sure you account for folio_ids_text in strong parameters. Also, it might be a good idea to dynamically associate objects/relations, instead of having to manually enter IDs :).

Upvotes: 1

Related Questions