record nil after post

0

I want to edit a record with an action in the controller but when the record is passed, nil arrives and of course I can not edit it. Attached the driver, the model and the view.

You can see the code on GitHub (it's a very basic code generated with Scaffold), I just want to highlight the error what gives me.

I am using the following local versions:

  • ruby 2.2.6p396 (2016-11-15 revision 56800) [i386-mingw32]
  • Rails 5.1.1

app \ controllers \ articulo_controller.erb

 def ajustar
    puts '------------------------------------------------------------'
    puts @articulo.inspect
  # @articulo.contenido = "ref:" + @articulo.contenido 
    puts '------------------------------------------------------------'
    redirect_to articulos_url
  end

app \ config \ routes.rb

Rails.application.routes.draw do
  resources :articulos
   post '/ajustar/:id' => 'articulos#ajustar', as: 'ajustar'
end

app \ view \ index.html.erb

<% @articulos.each do |articulo| %>
  <tr>
    <td><%= articulo.nombre %></td>
    <td><%= articulo.titulo %></td>
    <td><%= articulo.contenido %></td>
    <td><%= link_to 'Show', articulo %></td>
    <td><%= link_to 'Edit', edit_articulo_path(articulo) %></td>
    *<td><%= link_to 'ajusar', **ajustar_url(articulo)**, method: :post %></td>*
    <td><%= link_to 'Destroy', articulo, method: :delete, data: { confirm: 'Are you sure?' } %></td>
  </tr>
<% end %>

log output

  

Started POST "/ adjust / 1" for 127.0.0.1 at 2017-06-23 13:29:28 -0400
  Processing by ArticulosController # adjust as HTML
  -------------------------------------------------- ---------- Nil
  -------------------------------------------------- ---------- Redirected to link Completed 302 Found in
  6ms (ActiveRecord: 0.0ms)


  Started GET "/ articles" for 127.0.0.1 at 2017-06-23 13:29:28 -0400
  Processing by ArticulosController # index as HTML Rendering
  articles / index.html.erb within layouts / application Article Load
  (2.0ms) SELECT "articles". * FROM "articles" Rendered
  articles / index.html.erb within layouts / application (12.0ms) Completed
  200 OK in 640ms (Views: 565.1ms | ActiveRecord: 2.0ms)


    
asked by rrg1459 23.06.2017 в 20:21
source

1 answer

1

The problem is that you are not assigning any value for @articulo , since the set_articulo method is not executed for the action ajustar , as shown in this line in your controller:

before_action :set_articulo, only: [:show, :edit, :update, :destroy]

To make it work, modify the previous line by adding the action ajustar :

before_action :set_articulo, only: [:show, :edit, :update, :destroy, :ajustar]

Now @articulo will already be defined in that action so it will no longer be nil .

    
answered by 23.06.2017 / 21:32
source