Search code examples
ruby-on-railsruby-on-rails-4callbackafter-save

Check for save after update Rails 4


An update method for one of my controllers looks like this:

def update
  @node = Node.find(params[:id])
  @video = @node.media
  @node.update(node_params)
  @video.update(title: @node.name, description: @node.description)
end

I need a callback to make sure that the @node and @video updated. What's the best way to do this?


Solution

  • You can test if the update succeeds...

      if @node.update(node_params)
        # handle success
        if @video.update(title: @node.name, description: @node.description)
          # etc...
        end
      else
        # handle fail
      end
    

    In an ajax request, you can put the condition in the view:

    <% if @node.errors.any? %>
      alert('<%= j(@node.errors.full_messages.join("\n")) %>');
    <% else %>
      alert('Success')
    <% end %>