Note that there are some explanatory texts on larger screens.

plurals
  1. POCreate new associated values from multiple select in rails using formtastic
    primarykey
    data
    text
    <p>Hello friends from stackoverflow.</p> <p>I am developing my website in rails and I have Viagens (Trips) and Destinos (Destinations) like follows:</p> <pre><code>class Viagem &lt; ActiveRecord::Base has_and_belongs_to_many :destinos </code></pre> <p>and</p> <pre><code>class Destinos &lt; ActiveRecord::Base has_and_belongs_to_many :viagens </code></pre> <p>Ok, I am able to create a Viagem and with multiple Destinos and etc using the following FORMTASTIC code in my view.</p> <pre><code>f.input :destinos, :as =&gt; :select, :input_html =&gt; {:multiple =&gt; 'multiple'} </code></pre> <p>But I want to be able to create new Destinos FROM the New Viagem View. My (failing) solution was to use Jquery to add Options to the Select input like. The options values output would be "id:name" so that I could then split in the controller. I could not manage to create the input with formtastic, so I change to regular rails:</p> <pre><code>&lt;%= f.select(:destinos, @destinos.collect{ |c| [c.nome, "#{c.id}:#{c.nome}"] }, { :selected =&gt; @viagem.destino_ids }, { multiple: true, size: 5}) %&gt; </code></pre> <p>This is my Controller:</p> <pre><code>def create params[:viagem][:destino_ids] = [] if params[:viagem][:destinos] a = params[:viagem][:destinos] a.each do |k| k.split(':') params[:viagem][:destino_ids] &lt;&lt; Destino.find_or_create_by_nome(k[1]).id end end params[:viagem].delete :destinos @viagem = @agencia.viagens.build(params[:viagem]) if @viagem &amp;&amp; @viagem.save redirect_to edit_agencias_viagem_path(@viagem), :notice =&gt; "A viagem foi salva!" else @destinos = Destino.all render :new end end def edit @viagem = Viagem.find_by_id(params[:id]) @destinos = Destino.all @destinos_viagem = @viagem.destino_idss end </code></pre> <p>The idea is to SAVE new Destinos and to Display the right Viagem.destinos when editing... How bad is my whole idea?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload