Search code examples
ruby-on-railsrubyruby-on-rails-2

Rails View doesn't update until refreshed but controller is updating database fine


This is the first time I've encountered this problem.

I have a view which submits a post request to a controller which updates two tables.

def update
  if request.post?
    if @circuit
      # update
      @circuit.update_attributes params[:circuit]

      @logical_interface = LogicalInterface.new params[:logical_interface]
      @logical_interface.save


      #redirect_to :action => 'update', :id => @circuit.id
      @success = "Updated." if @circuit.valid?
    else
      # attempt create
    end
  end
end

These three lines are what I've added to the controller:

@logical_interface = LogicalInterface.new params[:logical_interface]
@logical_interface.save


redirect_to :action => 'update', :id => @circuit.id # this was added because the view wasn't being updated until refreshed

If I keep the redirect, the view will be updated accordingly but I get no Updated. message in the @success variable.

If I comment out the redirect, the circuit form fields at the top of my form will update but not the table of logical_interfaces that I am adding to but I still get the Updated. success message. Everything is in the view directly, no partials are used.

Hopefully I've explained it properly but if anyone is unsure then I can update the question to go into more detail.

The form is just:

<%= form_tag :controller => "circuit", :action => "update" %>
    ...
</form>

In the form I use two objects circuit and logical_interface to split up the inputs so that in the controller I can update the circuit and create a new logical_interface.


Solution

  • try to adjust positions of redirect_to and @success, I think redirect_to should be the last line of the block.

    And If you use redirect_to, you will lose all your instance variables, so better way is using flash.

    in your controller:

    flash[:notice] = "Updated." if @circuit.valid?    
    redirect_to :action => 'update', :id => @circuit.id
    

    in your page:

    <p><%= flash[:notice]%></p>