Rails - how to update a single attribute in a controller

I am new to rails and try to achieve a simple task. I want to switch the boolean attribute "done" to the image click. In my opinion, my link looks like this:

<%= link_to image_tag("done.png"),
    feed_item,
    :controller => :calendars, :action=>:toggle_done,:id=> feed_item.id,
    :title => "Mark as done", :remote=> true, :class=>"delete-icon" %>

I added the route as follows:

resources :calendars do
    get 'toggle_done', :on => :member
end

in the controller, I created a method:

def toggle_done
    @calendar = Calendar.find(params[:id])
    toggle = !@calendar.done
@calendar.update_attributes(:done => toggle)

respond_to do |format|
  flash[:success] = "Calendar updated"
  format.html { redirect_to root_path }
  format.js
end

When I click on the image, nothing happens, I see the following error:

Started GET "/toggle_done" for 127.0.0.1 at 2010-12-27 13:56:38 +0530
ActionController::RoutingError (No route matches "/toggle_done"):

I am sure that there is something very trivial that I am missing here.

+3
source share
3 answers

Just FYI, ActiveRecord provides “toggle” and “toggle!”. Methods performed in exactly the same way as a name claim for a given attribute.

Route →

resources :calendars do
  member do
    put :toggle_done
  end
end

(, HTTP-). GET RESTful. →

<%= link_to image_tag("done.png"), feed_item, toggle_done_calendars_path(feed_item)
    :title => "Mark as done", :remote=> true, :class=>"delete-icon", :method => :put %>

def toggle_done
  @calendar = Calendar.find(params[:id])
  @calendar.toggle!(:done)

  respond_to do |format|
    flash[:success] = "Calendar updated"
    format.html { redirect_to root_path }
    format.js
  end
end
+8

link_to URL-, Active Record , :controller/:action. Active Record (feed_item) :controller/:action, :controller/:action.

, URL HTML-, , .

, :

<%= link_to image_tag("done.png"),
    { :controller => :calendars, :action =>:toggle_done, :id => feed_item.id },
    { :title => "Mark as done", :remote => true, :class =>"delete-icon" } %>
+2

- : link_to .

: . /calendars/path, /toggle _done. , /toggle _done: controller = > : calendars,: action = > : toggle_done

match :toggle_done => "calendars#toggle_done"

, RESTful. , , _, , toggle_done _. PUT.

resources :calendars do
  resources :feed_items do
    put :toggle_done, :on => member
  end
end

//1/feed_items/2/toggle_done, feed_item 2 1.

0

Source: https://habr.com/ru/post/1782250/


All Articles