Search code examples
ruby-on-railsrubymodelruby-on-rails-3.2update-attribute

Rails update_attribute not found


i need update a single record attribute but i can´t. alumno_id is foreign key of model 'alumno'. the code show the records and if submit 'Aceptar' in one record, need a change the attribute estado to 1

in Model

class Postulacion < ActiveRecord::Base
  attr_accessible :ramo, :estado, :alumno_id
  belongs_to :alumno
end

in View

<h1>Lista de Postulaciones</h1>
<% @postulaciones.each do |p| %>
<% @id = p.id %>
<%= @id %>
<p>
<td><%= Alumno.find(p.alumno_id).full_name%></td>
<td><%='=> '+ p.ramo %></td>
<td><% if p.estado == 0 %>
    <%= 'Pendiente =>' %>
    <%= form_tag :action => 'aceptar' do %>
    <%= submit_tag 'Aceptar' %></p>
    <%end%>
    <%else%>
    <%='=>  Aceptado' %>
    <%end%>
</td>
</p>
<% end %>

in controller

class ListadoController < ApplicationController
  def listar   
    @postulaciones = Postulacion.all
    respond_to do |format|
      format.html 
      format.json { render json: @postulaciones }
    end  
  end
 def aceptar
  @postulacion = Postulacion.where(id: @id).first #Edit
      @postulacion.estado = 1 #Edit
      @postulacion.save #Edit
  redirect_to "/" 

end end

Error "undefined method `update_attribute' for []:ActiveRecord::Relation"

Thanks


Solution

  • With this code:

     @postulacion = Postulacion.where(alumno_id: @id )
    

    You are declaring @postulacion as a collection, not as a single instance. You can fix this by calling .first:

     @postulacion = Postulacion.where(alumno_id: @id ).first
    

    Or by using find_by instead of where:

     @postulacion = Postulacion.find_by(alumno_id: @id )
    

    One other thing - this code isn't checking for the possibility that the Postulacion instance might not exist. You should add some logic to handle this...