web-wolf
web-wolf

Reputation: 91

How to update Item with one click?

I want to update Item that are stored in my DB with one click. For example i have model called Car. It has attribute called "active" which is Boolean so could be 0 or 1 in DB. I want that users have a possibility to change this this attribute with one click for example from index page of their cars. I know that it could be done if i would make this button like the whole form. But i think it is not the best solution and not right. Could i make it in any another way, maybe create special link_to or something like this? As i understand it should send request to CarsController into update method, but how to do this without form?

Upvotes: 0

Views: 368

Answers (3)

Nayeem Baig
Nayeem Baig

Reputation: 1

I know I'm late but adding this answer for new rails developers

You simply need to use link_to with remote: true. If link_to throws routing error then use button_to instead For example in your view:

button_to "Activate", car_path(@car.id), method: :patch, remote: true

And in your controller method:

def active
  @car = Car.find(params[:id])
  @car.update(active: true)
  redirect_to cars_path(@cars), status: :see_other
end

And in your routes.rb :

resources :cars do
      member do
        patch :active
      end
    end

Upvotes: 0

Parakh Garg
Parakh Garg

Reputation: 119

If you are using jquery, you can use jquery ajax method with dataType as JSON. And you can also use the same restful update method i.e without creating any new method.

View - <%= button_tag 'Activate', car_id: "22" , id: "activate_car" %>

Controller -

  def update
    @car = Car.find(params[:id])
    respond_to do |format|
      if @car.update(car_params)
        format.html { redirect_to @car, notice: 'Car was successfully updated.' }
        format.json { render :json: 'Successfully update' }
      else
        format.html { render :edit }
        format.json { render json: @car.errors }
      end
    end
  end

  private

  def car_params
      params.require(:car).permit(:active)
  end

JS -

$(document).on("click", '#activate_car', function () {
  car_id = $(this).attr('car_id')
  $.ajax({
    url: "/cars/" + car_id,
    type: "PUT",
    data: {
      active: true
    },
    dataType: "json",
    success: function (response) {
      alert(response)
    }
  });
});

Upvotes: 0

NN796
NN796

Reputation: 1267

You simply need to use link_to with remote: true. For example in your view:

link_to "Activate", car_path(@car.id), method: :post, remote: true

And in your controller method:

def active
  @car = Car.find(params[:id])
  @car.update(active: true)
  render json: :ok
end

A complete guide present here.

Upvotes: 4

Related Questions