0
votes

If I have the @mis_clases array variable in the controller:

bloques_controller

def new
  @bloque = Bloque.new
  @mis_clases = Array.new
end

And I try to pass it to view, to fill it with clases:

form.html.erb

<div class="card-body">
  <%= form.fields_for :clases do |clase| %>
    <%= render partial: 'clase_fields' %>
    <% @mis_clases << clase %>
  <% end %>
</div>

And access it back in the controller:

bloques_controller

  def create

    @bloque = Bloque.new(bloque_params)

    @mis_clases.each do |clase|
      # Do something
    end

    ...

  end

I want to access the variable again when I save the form, but it throws this error: enter image description here

1
You can share a variable from controller to view by creating an instance variable but you cannot do same other way round. You need to use session to keep the value floating between request because http is stateless protocol. - Amit Patel

1 Answers

1
votes

The naming instance variable might be little misleading, but you need to remember that every new request to controller goes to new instance of Controller Class, so even if you create @mis_clases in #new, when reaching #create there is new instance without any variables set, and having nothing in common with recent one but class name. You should pass variables as field values in form.