Acrux
Acrux

Reputation: 406

How to update rows from view button click<RoR>

I'm trying to build a ruby on rails application where several rows of data get updated when a user clicks on a button. Whenever i click the button I get a ActiveRecord::StatementInvalid in PagesController#call_action SQLite3::SQLException: no such column: attendances.2 error. I'm guessing that the data is not passed correctly hence the find is not working but i'm not sure why it's not working.

What's in the view

<%= link_to 'Approve',
            {controller: 'pages',
             action: 'call_action',
             store_id: @store.id,
             period_id: period.id},
            class: 'button' %>

my pages_controller.rb

def call_action

    @attendances = Attendance.where(params[:store_id] => :store_id,params[:period_id] => :period_id)
    .update_all(status: "Approved")
        if @attendances!=nil
         @attendances.each do |var|
            var.save!
         end
         redirect_to root_path
      end
end

My routes file

get '/pages/call_action' => 'pages#call_action', :as => :call_action

My schema

create_table "attendances", force: :cascade do |t|
    t.integer "period_id", null: false
    t.integer "employee_id", null: false
    t.integer "store_id", null: false
    t.decimal "hours_assigned"
    t.decimal "hours_worked"
    t.decimal "days_worked"
    t.decimal "regular_holidays_worked"
    t.decimal "special_holidays_worked"
    t.decimal "leaves"
    t.decimal "rest_days"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.integer "oic"
    t.string "status"
    t.index ["employee_id"], name: "index_attendances_on_employee_id"
    t.index ["period_id"], name: "index_attendances_on_period_id"
    t.index ["store_id"], name: "index_attendances_on_store_id"
  end

What i get in the terminal

Processing by PagesController#call_action as HTML
  Parameters: {"period_id"=>"9", "store_id"=>"2"}
  User Load (0.3ms)  SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ?  [["id", 3], ["LIMIT", 1]]
  Attendance Update All (0.8ms)  UPDATE "attendances" SET "status" = ? WHERE "attendances"."2" = ? AND "attendances"."9" = ?  [["status", "Approved"], ["2", "store_id"], ["9", "period_id"]]
  ↳ app/controllers/pages_controller.rb:13:in `call_action'
Completed 500 Internal Server Error in 6ms (ActiveRecord: 1.0ms | Allocations: 2936)

Upvotes: 0

Views: 169

Answers (1)

Saif Chaudhry
Saif Chaudhry

Reputation: 449

Update All returns number of records updated. So @attendances will have number not records. You should do something like

@attendances = Attendance.where(store_id: params[:store_id],
                               period_id: params[:period_id]) 
@attendances.update_all(status: "Approved")

And there is no need of iteration

Upvotes: 1

Related Questions